如何向Laravel 5.6中的所有日志记录添加数据?

How to add data to all log records in Laravel 5.6?

How to add data to all log records in Laravel? 回答了如何向 Laravel 5.5 及更早版本的所有日志记录添加数据。例如以下添加到 AppServiceProvider::register():

$monolog = \Log::getMonolog();
$monolog->pushProcessor(function ($record) {
    $record['extra']['ip'] = \Request::getClientIp();
    $record['extra']['path'] = \Request::path();
    return $record;
});

这不适用于 Laravel 5.6。我查看了 'creating custom channels' 的文档,但没有看到任何明显的方法来获得上述行为。

错误发生自

@php artisan package:discover -v

Symfony\Component\Debug\Exception\FatalThrowableError  : Call to undefined method Monolog\Logger::getMonolog()

at ...\vendor\laravel\framework\src\Illuminate\Log\Logger.php: 273
269:      * @return mixed
270:      */
271:     public function __call($method, $parameters)
272:     {
273:         return $this->logger->{$method}(...$parameters);
274:     }
275: }
276:

Exception trace:

1   Illuminate\Log\Logger::__call("getMonolog", [])

...\vendor\laravel\framework\src\Illuminate\Log\LogManager.php : 609

2   Illuminate\Log\LogManager::__call("getMonolog", [])

...\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php : 223

Please use the argument -v to see more details.

我远不是这方面的专家,因此非常感谢您的帮助。

这是我解决这个问题的方法。

  1. 在 .env 中,使用 'stack channel' 进行日志记录(即 'LOG_CHANNEL=stack')
  2. 在config\logging中为驱动程序添加'tap'。php

    'single' => [
        'driver' => 'single',
        'tap' => [App\Logging\CustomizeFormatter::class],
        'path' => storage_path('logs/laravel.log'),
        'level' => 'debug',
    ]
    
  3. 创建App\Logging\CustomizeFormatter:

    namespace App\Logging;
    
    class CustomizeFormatter
    {
        public function __invoke($logger)
        {
            foreach ($logger->getHandlers() as $handler) {
                $handler->pushProcessor(function ($record) {
                    $record['extra']['ip'] = \Request::getClientIp();
                    $record['extra']['path'] = \Request::path();
    
                    return $record;
                });
            }
        }
    }