How to add data to all log records in Laravel?

Since Laravel comes out of box with Monolog, it is pretty straight forward. It can be easily achieved by editing app/start/global.php and add 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;
});

Basically, we are using the underlying Monolog instance to register a processor which will intercept any log record to be written. The results will be similar as the followings:

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

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


Extra: The hardcoded extra is to tell Monolog to add data as extra piece of information (redundant to say). In the practice, this is to avoid overriding any context data added in the original log call.


In Laravel 5 you can do it by customising Monolog. First create a class which customises Monolog so it adds the user information to the log records:

namespace App\Logging;

use App\Models\User;
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Log\Logger;

class AddUserInformation
{
    protected $request;

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

    public function __invoke(Logger $logger)
    {
        if ($this->request) {
            foreach ($logger->getHandlers() as $handler) {
                $handler->pushProcessor([$this, 'processLogRecord']);
            }
        }
    }

    public function processLogRecord(array $record): array
    {
        $record['extra'] += [
            'user' => $this->request->user()->username ?? 'guest',
            'ip' => $this->request->getClientIp()
        ];

        return $record;
    }
}

Then connect the class to the Laravel logger by adding it to the channel setup in the config/logging.php file:

// ...
'channels' => [
    'single' => [
        'driver' => 'single',
        'tap' => [\App\Logging\AddUserInformation::class],
        'path' => storage_path('logs/laravel.log'),
        'level' => env('LOG_LEVEL', 'debug'),
    ],
    // ...
]

A documentation about customising Monolog