Home » Code » 更改Laravel默认的日志格式

更改Laravel默认的日志格式

Laravel 日志使用的是 Monolog 库,默认的 formatter 是 LineFormatter。

要更换 formatter ,只需要在配置文件 logging.php 中设置”formatter”参数:

在 CustomFormatter 中,继承自默认的 LineFormatter ,修改下格式即可:

namespace App\Logging;

use Monolog\Formatter\LineFormatter;

class CustomFormatter extends LineFormatter
{
    public function __construct(?string $format = null, ?string $dateFormat = null, bool $allowInlineLineBreaks = false, bool $ignoreEmptyContextAndExtra = false)
    {
        // 默认格式:"[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n";
        $format = sprintf("%s %s auth:%s %s", "[%datetime%]", REQUEST_ID, auth()->id() ?? 0, "%channel%.%level_name%: %message% %context% %extra%\n");
        $ignoreEmptyContextAndExtra = true;
        parent::__construct($format, $dateFormat, $allowInlineLineBreaks, $ignoreEmptyContextAndExtra);
    }
}

在这里,我在时间后边添加了 REQUEST_ID,这是一个常量,并且把当前认证用户的ID也一并记录,其他保持不变。最终的日志如下:


\Log::info(__METHOD__, ["a" => 1, "b" => 2]);
[2019-03-16 17:55:00] 5c8cc7f43ec31156831057 auth:0 local.INFO: App\Console\Commands\Test::handle {"a":1,"b":2}

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Time limit is exhausted. Please reload CAPTCHA.