Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Laravel can I set a default context for the Log facade

Tags:

php

laravel

I'm using the Log:: facade a lot and have a helper class called LogHelper which provide me with a static method LogHelper::context() which include many key values I need to track the requests. But having to type it every time for each usage make it error prune and fill not so efficient.

I'm looking for a way to inject the values by default, and allow me to overwrite them if needed specifically.

At the moment this is how I use it,

Log::debug('Request Started', LogHelper::context());

what I'm looking for is to inject the context by default

Log::debug('Request Started');

and have the option to overwrite it, if need it:

Log::debug('Request Started', ['more' => 'context'] + LogHelper::context());

PS, the LogHelper::context() return a simple key => value array which include some staff i need to debug requests, and the reason it do not use the values directly in the message is because i log to graylog as structured data, and this way i can filter by any key.

like image 331
Rabin Avatar asked Oct 30 '25 14:10

Rabin


2 Answers

I have solved this issue by using the tap functionality and $logger->withContext() (note: the latter was added in Laravel 8.49).

You want to create a new class which contains your context logic. I've created an extra Logging folder in app/ in which my logging customizations sit.

app/Logging/WithAuthContext.php:

<?php

namespace App\Logging;

use Illuminate\Log\Logger;

class WithAuthContext
{
    public function __invoke(Logger $logger)
    {
        $logger->withContext([
            'ip' => request()?->ip(),
            'ua' => request()?->userAgent(),
        ]);
    }
}

Depending on which logging channel(s) you use, you will have to add the class to each one you want to add context to. So in app/config/logging.php:

<?php

use App\Logging\WithAuthContext;
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;

return [
// ...
    'channels' => [
        // ...
        'single' => [
            'driver' => 'single',
            'path' => storage_path('logs/laravel.log'),
            'level' => env('LOG_LEVEL', 'debug'),
            'tap' => [WithAuthContext::class],
        ],
        // ...
    ],
];
like image 135
Bram van Dalen Avatar answered Nov 01 '25 05:11

Bram van Dalen


Laravel 11.x added Context class, allowing you to set the context of the request. Context will automatically added to logs. See documentation https://laravel.com/docs/11.x/context#how-it-works

like image 37
Abrar Ahmad Avatar answered Nov 01 '25 06:11

Abrar Ahmad