问题
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.
- In .env, use the 'stack channel' for logging (i.e. 'LOG_CHANNEL=stack')
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', ]
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