-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLogTrait.php
More file actions
63 lines (58 loc) · 1.77 KB
/
LogTrait.php
File metadata and controls
63 lines (58 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?php
namespace WebmanTech\CrontabTask\Traits;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use WebmanTech\CommonUtils\Log;
use WebmanTech\CrontabTask\Helper\ConfigHelper;
trait LogTrait
{
/**
* 日志 channel
* @var string|null
*/
protected ?string $logChannel = null;
/**
* 默认的日志级别
* @var string|null
*/
protected ?string $logType = null;
/**
* 是否记录 class
* 如果 logChannel 是独立的,可以选择关闭
* @var bool|null
*/
protected ?bool $logClass = null;
/**
* @var ?LoggerInterface
*/
protected ?LoggerInterface $logger = null;
/**
* log
* @param string $msg
* @param string|null $type
* @return void
*/
protected function log(string $msg, ?string $type = null)
{
if ($this->logger === null) {
$config = array_merge(
['channel' => null, 'type' => 'info', 'log_class' => true],
array_filter((array)ConfigHelper::get('app.log', []), fn($value) => $value !== null),
array_filter(['channel' => $this->logChannel, 'type' => $this->logType, 'log_class' => $this->logClass], fn($value) => $value !== null),
);
if (!$config['channel']) {
$this->logger = new NullLogger();
} else {
$this->logChannel = (string)$config['channel'];
$this->logType = $config['type'];
$this->logClass = $config['log_class'];
$this->logger = Log::channel((string)$config['channel']);
}
}
$type ??= $this->logType ?? 'info';
if ($this->logClass) {
$msg = static::class . ':' . $msg;
}
$this->logger->{$type}($msg);
}
}