Laravel/Lumen Customizing Monolog For Channels

官方文档 https://laravel.com/docs/6.x/logging#creating-monolog-handler-channels

首先 新建一个 文件:

App\Logging\CustomizeFormatter.php

如官方文档所示,可以在 __invoke 方法里定制你的 logger,例如你想要 json 格式的日志的话:

foreach ($logger->getHandlers() as $handler) {
    $handler->setFormatter(new JsonFormatter());
}

更多设置:

<?php

namespace App\Logging;

use Illuminate\Http\Request;
use Illuminate\Log\Logger;
use Monolog\Formatter\JsonFormatter;
use Monolog\Logger as Monologger;
use Monolog\Processor\IntrospectionProcessor;
use Monolog\Processor\MemoryUsageProcessor;
use Monolog\Processor\ProcessIdProcessor;
use Monolog\Processor\WebProcessor;

class CustomizeFormatter
{
    protected $request;

    public function __construct(Request $request = null)
    {
        $this->request = $request;
    }

    /**
     * Customize the given logger instance.
     *
     * @param  \Illuminate\Log\Logger  $logger
     * @return void
     */
    public function __invoke(Logger $logger)
    {
        if ($this->request) {
            foreach ($logger->getHandlers() as $handler) {
                $handler->setFormatter(new JsonFormatter());
                $handler->pushProcessor(new IntrospectionProcessor($handler->getLevel(), [], 4));
                $handler->pushProcessor(new MemoryUsageProcessor());
                $handler->pushProcessor(new WebProcessor());
                $handler->pushProcessor(new ProcessIdProcessor);
                $handler->pushProcessor([$this, 'headerProcessor']);
            }
        }
    }

    public function headerProcessor(array $record): array
    {
        $record['extra'] += [
            'user_id' => $this->request->header('X-User-Id', 'guest'),
            'roles' => $this->request->header('X-Roles', 'NULL'),
        ];

        return $record;
    }
}

输出的日志样本如下:

{
    "message": "Undefind method: \"asdasdad\"",
    "context": {},
    "level": 400,
    "level_name": "ERROR",
    "channel": "local",
    "datetime": "2020-05-11T17:05:07.231673+08:00",
    "extra": {
        "user_id": "guest",
        "roles": "NULL",
        "process_id": 13,
        "url": "/data/v1/download?action=asdasdad&token=1",
        "ip": "172.25.0.1",
        "http_method": "GET",
        "server": "_",
        "referrer": null,
        "memory_usage": "2 MB",
        "file": "/var/www/html/app/Http/Controllers/DownloadController.php",
        "line": 69,
        "class": "App\\Http\\Controllers\\DownloadController",
        "function": "init"
    }
}