laravel logs

为laravel logs添加自定义格式与处理方法

Monolog\Formatter\LineFormatter 用来定义log内容。

Monolog\Processor\IntrospectionProcessor 用来获取控制器、方法、行数。

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
<?php

namespace App\Logging;

use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Processor\IntrospectionProcessor;

// 接收log
class TestLogging
{
private $logFormat = "";
private $dateFormat = 'Y/m/d H:i:s';

public function __construct()
{
// 设置行内容
$cols = [
"%datetime%",
"[%channel%.%level_name%]",
"%extra.class%@%extra.function%(%extra.line%)",
"%message%",
"%context%",
];

// 成表格
$this->logFormat = implode("\t", $cols) . PHP_EOL;
}

public function __invoke($monolog)
{
// 定义新的日记样式
$formatter = new LineFormatter($this->logFormat, $this->dateFormat, true, true);

// 控制器 内容追加
$ip = new IntrospectionProcessor(Logger::DEBUG, [] , 4);

foreach ($monolog->getHandlers() as $handler) {
$handler->setFormatter($formatter);
$handler->pushProcessor($ip);
}
}
}

设置logging.php

1
2
3
4
5
6
7
'daily' => [
'driver' => 'daily',
'tap' => [App\Logging\TestLogging::class],
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
'days' => 14,
],

参考1
参考2