Passed
Push — develop ( ba5262...9c69c6 )
by nguereza
04:59
created

AbstractLoggerHandler::format()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 17
nc 4
nop 3
dl 0
loc 21
rs 9.7
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Platine Logger
5
 *
6
 * Platine Logger is the implementation of PSR 3
7
 *
8
 * This content is released under the MIT License (MIT)
9
 *
10
 * Copyright (c) 2020 Platine Logger
11
 *
12
 * Permission is hereby granted, free of charge, to any person obtaining a copy
13
 * of this software and associated documentation files (the "Software"), to deal
14
 * in the Software without restriction, including without limitation the rights
15
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
 * copies of the Software, and to permit persons to whom the Software is
17
 * furnished to do so, subject to the following conditions:
18
 *
19
 * The above copyright notice and this permission notice shall be included in all
20
 * copies or substantial portions of the Software.
21
 *
22
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
 * SOFTWARE.
29
 */
30
31
/**
32
 *  @file AbstractLoggerHandler.php
33
 *
34
 *  The AbstractLoggerHandler class that all logger handler must extend it.
35
 *
36
 *  @package    Platine\Logger
37
 *  @author Platine Developers Team
38
 *  @copyright  Copyright (c) 2020
39
 *  @license    http://opensource.org/licenses/MIT  MIT License
40
 *  @link   http://www.iacademy.cf
41
 *  @version 1.0.0
42
 *  @filesource
43
 */
44
45
declare(strict_types=1);
46
47
namespace Platine\Logger;
48
49
use DateTime;
50
use DateTimeImmutable;
51
use DateTimeInterface;
52
use Throwable;
53
54
abstract class AbstractLoggerHandler implements LoggerHandlerInterface
55
{
56
    /**
57
     * All The handler configuration
58
     * @var array<string, mixed>
59
     */
60
    protected array $config = [];
61
62
       /**
63
     * Channel used to identify each log message
64
     * @var string
65
     */
66
    protected string $channel = 'MAIN';
67
68
    /**
69
     * Whether to log to standard out.
70
     * @var boolean
71
     */
72
    protected bool $stdout = false;
73
74
    /**
75
     * Log fields separated by tabs to form a TSV (CSV with tabs).
76
     * @var string
77
     */
78
    protected string $tab = "\t";
79
80
    /**
81
     * Create new logger handler instance
82
     *
83
     * @param array<string, mixed> $config
84
     */
85
    public function __construct(array $config = [])
86
    {
87
        $this->config = $config;
88
89
        if (isset($config['channel'])) {
90
            $this->channel = $config['channel'];
91
        }
92
93
        if (isset($config['stdout']) && is_bool($config['stdout'])) {
94
            $this->stdout = $config['stdout'];
95
        }
96
    }
97
98
    /**
99
     * Set the handler configuration
100
     *
101
     * @param array<string, mixed> $config
102
     *
103
     * @return self
104
     */
105
    public function setConfig(array $config): self
106
    {
107
        $this->config = $config;
108
109
        return $this;
110
    }
111
112
    /**
113
     * Return the handler configuration
114
     * @return array<string, mixed>
115
     */
116
    public function getConfig(): array
117
    {
118
        return $this->config;
119
    }
120
121
    /**
122
     * Set log channel
123
     *
124
     * @param string $channel
125
     *
126
     * @return self
127
     */
128
    public function setChannel(string $channel): self
129
    {
130
        $this->channel = $channel;
131
132
        return $this;
133
    }
134
135
    /**
136
     * Set the standard out option on or off.
137
     * If set to true, log lines will also be printed to standard out.
138
     *
139
     * @param bool $stdout
140
     *
141
     * @return self
142
     */
143
    public function setOutput(bool $stdout = true): self
144
    {
145
        $this->stdout = $stdout;
146
147
        return $this;
148
    }
149
150
151
    /**
152
     * {@inheritdoc}
153
     */
154
    abstract public function log(
155
        $level,
156
        string $message,
157
        array $context = []
158
    ): void;
159
160
    /**
161
     * Format the log line.
162
     * YYYY-mm-dd HH:ii:ss.uuuuuu  [loglevel]  [channel]  [pid:##]
163
     *  Log message content  {"Optional":"Exception Data"}
164
     * @param  string $level
165
     * @param  string $message
166
     * @param  array<string, mixed>  $context
167
     * @return string
168
     */
169
    protected function format(string $level, string $message, array $context): string
170
    {
171
        $exception = null;
172
        if (isset($context['exception']) && $context['exception'] instanceof Throwable) {
173
            $exception = print_r(
174
                $this->getExceptionData($context['exception']),
175
                true
176
            );
177
            unset($context['exception']);
178
        }
179
        $message = $this->interpolate($message, $context);
180
        $level = strtoupper($level);
181
        $pid = getmygid();
182
        return
183
                $this->getLogTime() . $this->tab .
184
                '[' . $level . ']' . $this->tab .
185
                '[' . $this->channel . ']' . $this->tab .
186
                '[pid:' . $pid . ']' . $this->tab .
187
                str_replace(\PHP_EOL, '   ', trim($message)) .
188
                ($exception ? ' ' . str_replace(\PHP_EOL, '   ', $exception) : '')
189
                    . \PHP_EOL;
190
    }
191
192
    /**
193
     * Get Exception information data
194
     * @param  Throwable $exception
195
     * @return array<string, mixed>        the exception data
196
     */
197
    protected function getExceptionData(Throwable $exception): array
198
    {
199
        return [
200
            'message' => $exception->getMessage(),
201
            'code' => $exception->getCode(),
202
            'file' => $exception->getFile(),
203
            'line' => $exception->getLine(),
204
            'trace' => $exception->getTraceAsString()
205
        ];
206
    }
207
208
    /**
209
     * Interpolates context values into the message placeholders.
210
     * @param  string $message
211
     * @param  array<string, mixed>  $context
212
     * @return string
213
     */
214
    protected function interpolate(string $message, array $context): string
215
    {
216
        if (strpos($message, '{') === false) {
217
            return $message;
218
        }
219
        $replacements = [];
220
        foreach ($context as $key => $value) {
221
            if (
222
                $value === null
223
                || is_scalar($value)
224
                || (is_object($value)
225
                && method_exists($value, '__toString'))
226
            ) {
227
                $replacements['{' . $key . '}'] = $value;
228
            } elseif ($value instanceof DateTimeInterface) {
229
                $replacements['{' . $key . '}'] = $value->format(DateTime::RFC3339);
230
            } elseif (is_object($value)) {
231
                $replacements['{' . $key . '}'] = '[object ' . get_class($value) . ']';
232
            } else {
233
                $replacements['{' . $key . '}'] = '[' . gettype($value) . ']';
234
            }
235
        }
236
        return strtr($message, $replacements);
237
    }
238
239
    /**
240
     * Get the current time for logging
241
     * Format: YYYY-mm-dd HH:ii:ss.uuuuuu
242
     * Microsecond precision for PHP 7.1 and greater
243
     *
244
     * @return string
245
     */
246
    protected function getLogTime(): string
247
    {
248
        return (new DateTimeImmutable('now'))->format('Y-m-d H:i:s.u');
249
    }
250
}
251