skip to Main Content

When using contextual information if logging in Laravel v10 (https://laravel.com/docs/10.x/logging#contextual-information), the contextual information doesn’t get merged when specifying the channel name.

e.g.: This works fine:

Log::info(
   'User {user} created Thing {id}', 
   [
      'user' => auth()->user()->id,
      'id' => $thing->id
   ]
);

…produces:

[2024-01-31 08:44:23] local.INFO: User 1 created Thing 3 {"user":1,"id":3} 

However, this doesn’t work:

Log::channel('mychannel')->info(
   'User {user} created Thing {id}',
   [
      'user' => auth()->user()->id,
      'id' => $thing->id
   ]
);

…as it produces:

[2024-01-31 08:36:15] local.INFO: User {user} created Thing {id} {"user":1,"id":2} 

Any idea what I’m doing wrong?

2

Answers


  1. Chosen as BEST ANSWER

    Whilst not covered in the documentation - in order to get this to work, you need to include the 'replace_placeholders' => true directive in the logging config, e.g.:

    config/logging.php:

    <?php
    ...
            'mychannel' => [
                'driver' => 'single',
                'path' => storage_path('logs/mychannel.log'),
                'level' => 'debug',
                'replace_placeholders' => true,
            ],
    

  2. To achieve the merging of contextual information with your log message when using a specific channel, you can manually merge the context into the log message using the withContext() method.

    use MonologHandlerStreamHandler;
    use MonologLogger;
    
    $log = new Logger('my_channel');
    $log->pushHandler((new StreamHandler('path/to/log/file'))->withContext(['user_id' => 123]));
    
    $log->info('User {user} created Thing {id}', ['user' => auth()->user()->id, 'id' => $thing->id]);
    

    To merge contextual information into log messages when using a specific channel in Laravel, you can follow the approach you mentioned earlier, where you manually merge the context into the log message

    Log::channel('mychannel')->info(
        'User {user} created Thing {id}',
        array_merge(
            ['user' => auth()->user()->id, 'id' => $thing->id],
            Log::getLogger()->getHandlers()[0]->getExtra()
        )
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search