Completed
Push — 6.0 ( 0d8b86...d391f8 )
by liu
04:21
created

Log::channelLog()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 4
nc 2
nop 3
dl 0
loc 7
ccs 0
cts 2
cp 0
crap 12
rs 10
c 1
b 0
f 0
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: liu21st <[email protected]>
10
// +----------------------------------------------------------------------
11
declare (strict_types = 1);
12
13
namespace think;
14
15
use InvalidArgumentException;
16
use Psr\Log\LoggerInterface;
17
18
/**
19
 * 日志管理类
20
 */
21
class Log implements LoggerInterface
22
{
23
    const EMERGENCY = 'emergency';
24
    const ALERT     = 'alert';
25
    const CRITICAL  = 'critical';
26
    const ERROR     = 'error';
27
    const WARNING   = 'warning';
28
    const NOTICE    = 'notice';
29
    const INFO      = 'info';
30
    const DEBUG     = 'debug';
31
    const SQL       = 'sql';
32
33
    /**
34
     * 日志信息
35
     * @var array
36
     */
37
    protected $log = [];
38
39
    /**
40
     * 日志通道
41
     * @var string
42
     */
43
    protected $channel;
44
45
    /**
46
     * 配置参数
47
     * @var array
48
     */
49
    protected $config = [];
50
51
    /**
52
     * 日志写入驱动
53
     * @var array
54
     */
55
    protected $driver = [];
56
57
    /**
58
     * 日志处理
59
     *
60
     * @var array
61
     */
62
    protected $processor = [
63
        '*' => [],
64
    ];
65
66
    /**
67
     * 关闭日志(渠道)
68
     * @var array
69
     */
70
    protected $close = [];
71
72
    /**
73
     * 是否控制台执行
74
     * @var bool
75
     */
76
    protected $isCli = false;
77
78
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $app should have a doc-comment as per coding-style.
Loading history...
79
     * 构造方法
80
     * @access public
81
     */
82 6
    public function __construct(App $app)
83
    {
84 6
        $this->config = $app->config->get('log');
85 6
86
        if (isset($this->config['processor'])) {
87 6
            $this->processor($this->config['processor']);
88
        }
89
90
        if (!empty($this->config['close'])) {
91 6
            $this->close['*'] = true;
92
        }
93
94
        $this->isCli = $app->runningInConsole();
95 6
        $this->channel();
96
    }
97
98
    /**
99
     * 获取日志配置
100
     * @access public
101
     * @return array
102
     */
103
    public function getConfig(): array
104
    {
105
        return $this->config;
106
    }
107
108
    /**
109
     * 注册一个日志回调处理
110
     *
111
     * @param  callable $callback 回调
112
     * @param  string   $channel  日志通道名
113
     * @return void
114
     */
115
    public function processor(callable $callback, string $channel = '*'): void
116
    {
117
        $this->processor[$channel][] = $callback;
118
    }
119
120
    /**
121
     * 切换日志通道
122
     * @access public
123
     * @param  string $name 日志通道名
124
     * @return $this
125
     */
126 6
    public function channel(string $name = '')
127
    {
128 6
        if ('' == $name) {
129 6
            $name = $this->config['default'] ?? 'think';
130
        }
131
132 6
        if (!isset($this->config['channels'][$name])) {
133 6
            throw new InvalidArgumentException('Undefined log config:' . $name);
134
        }
135
136
        $config = $this->config['channels'][$name];
137
138
        if (isset($config['processor'])) {
139
            $this->processor($config['processor'], $name);
140
        }
141
142
        if (!empty($config['close'])) {
143
            $this->close[$name] = true;
144
        }
145
146
        $this->channel = $name;
147
        return $this;
148
    }
149
150
    /**
151
     * 实例化日志写入驱动
152
     * @access public
153
     * @param  string $name 日志通道名
154
     * @return object
155
     */
156
    protected function driver(string $name = '')
157
    {
158
        $name = $name ?: $this->channel;
159
160
        if (!isset($this->driver[$name])) {
161
            $config = $this->config['channels'][$name];
162
            $type   = !empty($config['type']) ? $config['type'] : 'File';
163
164
            $this->driver[$name] = App::factory($type, '\\think\\log\\driver\\', $config);
165
        }
166
167
        return $this->driver[$name];
168
    }
169
170
    /**
171
     * 获取日志信息
172
     * @access public
173
     * @param  string $channel 日志通道
174
     * @return array
175
     */
176
    public function getLog(string $channel = ''): array
177
    {
178
        $channel = $channel ?: $this->channel;
179
        return $this->log[$channel] ?? [];
180
    }
181
182
    /**
183
     * 记录日志信息
184
     * @access public
185
     * @param  mixed  $msg       日志信息
0 ignored issues
show
Coding Style introduced by
Expected 5 spaces after parameter name; 7 found
Loading history...
186
     * @param  string $type      日志级别
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 6 found
Loading history...
187
     * @param  array  $context   替换内容
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
188
     * @return $this
189
     */
190
    public function record($msg, string $type = 'info', array $context = [])
191
    {
192
        if (!empty($this->close['*']) || !empty($this->close[$this->channel])) {
193
            return;
194
        }
195
196
        if (is_string($msg) && !empty($context)) {
197
            $replace = [];
198
            foreach ($context as $key => $val) {
199
                $replace['{' . $key . '}'] = $val;
200
            }
201
202
            $msg = strtr($msg, $replace);
203
        }
204
205
        if (isset($this->config['type_channel'][$type])) {
206
            $channels = (array) $this->config['type_channel'][$type];
207
            foreach ($channels as $channel) {
208
                $this->channelLog($channel, $msg, $type);
209
            }
210
        } else {
211
            $this->channelLog($this->channel, $msg, $type);
212
        }
213
214
        return $this;
215
    }
216
217
    /**
218
     * 记录通道日志
219
     * @access public
220
     * @param  string $channel 日志通道
221
     * @param  mixed  $msg  日志信息
0 ignored issues
show
Coding Style introduced by
Expected 5 spaces after parameter name; 2 found
Loading history...
222
     * @param  string $type 日志级别
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
223
     * @return void
224
     */
225
    protected function channelLog(string $channel, $msg, string $type): void
226
    {
227
        if ($this->isCli || !empty($this->config['channels'][$channel]['realtime_write'])) {
228
            // 实时写入
229
            $this->write($msg, $type, true, $channel);
230
        } else {
231
            $this->log[$channel][$type][] = $msg;
232
        }
233
    }
234
235
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $log should have a doc-comment as per coding-style.
Loading history...
236
     * 记录批量日志信息
237
     * @access public
238
     * @param  array  $msg  日志信息
0 ignored issues
show
Coding Style introduced by
Doc comment for parameter $msg does not match actual variable name $log
Loading history...
239
     * @param  string $type 日志级别
240
     * @return $this
241
     */
242
    public function append(array $log, string $type = 'info')
243
    {
244
        if (!empty($this->close['*']) || !empty($this->close[$this->channel]) || empty($log)) {
245
            return $this;
246
        }
247
248
        if (isset($this->log[$this->channel][$type])) {
249
            $this->log[$this->channel][$type] += $log;
250
        } else {
251
            $this->log[$this->channel][$type] = $log;
252
        }
253
254
        return $this;
255
    }
256
257
    /**
258
     * 清空日志信息
259
     * @access public
260
     * @param  string  $channel 日志通道名
261
     * @return $this
262
     */
263
    public function clear(string $channel = '')
264
    {
265
        if ($channel) {
266
            $this->log[$channel] = [];
267
        } else {
268
            $this->log = [];
269
        }
270
271
        return $this;
272
    }
273
274
    /**
275
     * 关闭本次请求日志写入
276
     * @access public
277
     * @param  string  $channel 日志通道名
278
     * @return $this
279
     */
280
    public function close(string $channel = '*')
281
    {
282
        $this->close[$channel] = true;
283
284
        $this->clear('*' == $channel ? '' : $channel);
285
286
        return $this;
287
    }
288
289
    /**
290
     * 保存日志信息
291
     * @access public
292
     * @return bool
293
     */
294
    public function save(): bool
295
    {
296
        if (!empty($this->close['*'])) {
297
            return true;
298
        }
299
300
        foreach ($this->log as $channel => $logs) {
301
            $result = $this->saveChannel($channel, $logs);
302
303
            if ($result) {
304
                $this->log[$channel] = [];
305
            }
306
        }
307
308
        return true;
309
    }
310
311
    /**
312
     * 保存某个通道的日志信息
313
     * @access protected
314
     * @param  string $channel 日志通道名
315
     * @param  array  $logs    日志信息
316
     * @return bool
317
     */
318
    protected function saveChannel(string $channel, array $logs = []): bool
319
    {
320
        if (!empty($this->close[$channel])) {
321
            return false;
322
        }
323
324
        // 日志处理
325
        $processors = $this->processor[$channel] ?? $this->processor['*'];
326
327
        foreach ($processors as $callback) {
328
            $logs = $callback($logs, $channel, $this);
329
330
            if (false === $logs) {
331
                return false;
332
            }
333
        }
334
335
        $log = [];
336
337
        foreach ($logs as $level => $info) {
338
            if (empty($this->config['level']) || in_array($level, $this->config['level'])) {
339
                $log[$level] = $info;
340
            }
341
        }
342
343
        return $this->driver($channel)->save($log);
344
    }
345
346
    /**
347
     * 实时写入日志信息
348
     * @access public
349
     * @param  mixed  $msg   调试信息
0 ignored issues
show
Coding Style introduced by
Expected 5 spaces after parameter name; 3 found
Loading history...
350
     * @param  string $type  日志级别
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 2 found
Loading history...
351
     * @param  bool   $force 是否强制写入
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
352
     * @param  string $channel  日志通道
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 2 found
Loading history...
353
     * @return bool
354
     */
355
    public function write($msg, string $type = 'info', bool $force = false, string $channel = ''): bool
356
    {
357
        // 封装日志信息
358
        if (empty($this->config['level'])) {
359
            $force = true;
360
        }
361
362
        $log = [];
363
364
        if (true === $force || in_array($type, $this->config['level'])) {
365
            $log[$type][] = $msg;
366
        } else {
367
            return false;
368
        }
369
370
        // 写入日志
371
        return $this->saveChannel($channel ?: $this->channel, $log);
372
    }
373
374
    /**
375
     * 记录日志信息
376
     * @access public
377
     * @param  string $level     日志级别
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 5 found
Loading history...
378
     * @param  mixed  $message   日志信息
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
379
     * @param  array  $context   替换内容
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
380
     * @return void
381
     */
382
    public function log($level, $message, array $context = []): void
383
    {
384
        $this->record($message, $level, $context);
385
    }
386
387
    /**
388
     * 记录emergency信息
389
     * @access public
390
     * @param  mixed  $message   日志信息
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
391
     * @param  array  $context   替换内容
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
392
     * @return void
393
     */
394
    public function emergency($message, array $context = []): void
395
    {
396
        $this->log(__FUNCTION__, $message, $context);
397
    }
398
399
    /**
400
     * 记录警报信息
401
     * @access public
402
     * @param  mixed  $message   日志信息
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
403
     * @param  array  $context   替换内容
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
404
     * @return void
405
     */
406
    public function alert($message, array $context = []): void
407
    {
408
        $this->log(__FUNCTION__, $message, $context);
409
    }
410
411
    /**
412
     * 记录紧急情况
413
     * @access public
414
     * @param  mixed  $message   日志信息
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
415
     * @param  array  $context   替换内容
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
416
     * @return void
417
     */
418
    public function critical($message, array $context = []): void
419
    {
420
        $this->log(__FUNCTION__, $message, $context);
421
    }
422
423
    /**
424
     * 记录错误信息
425
     * @access public
426
     * @param  mixed  $message   日志信息
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
427
     * @param  array  $context   替换内容
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
428
     * @return void
429
     */
430
    public function error($message, array $context = []): void
431
    {
432
        $this->log(__FUNCTION__, $message, $context);
433
    }
434
435
    /**
436
     * 记录warning信息
437
     * @access public
438
     * @param  mixed  $message   日志信息
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
439
     * @param  array  $context   替换内容
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
440
     * @return void
441
     */
442
    public function warning($message, array $context = []): void
443
    {
444
        $this->log(__FUNCTION__, $message, $context);
445
    }
446
447
    /**
448
     * 记录notice信息
449
     * @access public
450
     * @param  mixed  $message   日志信息
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
451
     * @param  array  $context   替换内容
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
452
     * @return void
453
     */
454
    public function notice($message, array $context = []): void
455
    {
456
        $this->log(__FUNCTION__, $message, $context);
457
    }
458
459
    /**
460
     * 记录一般信息
461
     * @access public
462
     * @param  mixed  $message   日志信息
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
463
     * @param  array  $context   替换内容
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
464
     * @return void
465
     */
466
    public function info($message, array $context = []): void
467
    {
468
        $this->log(__FUNCTION__, $message, $context);
469
    }
470
471
    /**
472
     * 记录调试信息
473
     * @access public
474
     * @param  mixed  $message   日志信息
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
475
     * @param  array  $context   替换内容
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
476
     * @return void
477
     */
478
    public function debug($message, array $context = []): void
479
    {
480
        $this->log(__FUNCTION__, $message, $context);
481
    }
482
483
    /**
484
     * 记录sql信息
485
     * @access public
486
     * @param  mixed  $message   日志信息
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
487
     * @param  array  $context   替换内容
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 3 found
Loading history...
488
     * @return void
489
     */
490
    public function sql($message, array $context = []): void
491
    {
492
        $this->log(__FUNCTION__, $message, $context);
493
    }
494
}
495