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

余生颓废 提交于 2019-12-02 18:11:53

问题


How to add data to all log records in Laravel? answers how to add data to all log records in Laravel 5.5 and earlier. e.g. the following is added to AppServiceProvider::register():

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

This doesn't work for Laravel 5.6. I looked through the documentation for 'creating custom channels' but didn't see any obvious way to get the above behavior.

The error occurs from

@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.

I am far from an expert at this so any help is appreciated.


回答1:


Here is how I solved this.

  1. In .env, use the 'stack channel' for logging (i.e. 'LOG_CHANNEL=stack')
  2. Add a 'tap' to a driver in config\logging.php

    'single' => [
        'driver' => 'single',
        'tap' => [App\Logging\CustomizeFormatter::class],
        'path' => storage_path('logs/laravel.log'),
        'level' => 'debug',
    ]
    
  3. Create 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;
                });
            }
        }
    }
    


来源:https://stackoverflow.com/questions/52032203/how-to-add-data-to-all-log-records-in-laravel-5-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!