How to add data to all log entries in Laravel?

I would like to add some data to all the log entries in my Laravel application.

I think it would be useful to know the username of the current user and / or the IP address of the client.

I am currently adding it manually by doing:

Log::info('Pre-paid activation.', array('username' => Auth::user()->username));

But I would like to know how to add an listener or do something so that all log entries have a username (if available).

+4
source share
1 answer

Since Laravel gets out of the box with Monolog , it's pretty straight forward. This can be easily done by editing app/start/global.phpand adding the following after the line that starts with Log::useFiles::

Log::useFiles(storage_path().'/logs/laravel.log');
$monolog = Log::getMonolog();
$monolog->pushProcessor(function ($record) {
    $record['extra']['user'] = Auth::user() ? Auth::user()->username : 'anonymous';
    $record['extra']['ip'] = Request::getClientIp();
    return $record;
});

, Monolog , , . :

[2014-04-12 23:07:35] local.INFO: . [] { "user": "", "ip": ":: 1" }

Monolog: https://github.com/Seldaek/monolog/blob/master/doc/01-usage.md#using-processors


: extra ( ). , .

+7

Source: https://habr.com/ru/post/1536278/


All Articles