For a Laravel 5.7 app I'd like to add an additional bit of info to the default log prefix.
A log entry currently looks like this:
[2020-05-13 13:07:42] production.INFO: Information here...
I'd like to extend the prefix to make it:
[2020-05-13 13:07:42] PREFIX.production.INFO: Information here...
With PREFIX
coming from an environment variable, LOG_PREFIX
:
LOG_CHANNEL=daily
LOG_PREFIX=PREFIX
I don't mind using a regex to change production.INFO to PREFIX.production.INFO in a custom formatter.
I have added a tap to the log channel:
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
'days' => 7,
'tap' => [App\Logging\CustomizeFormatter::class],
]
It's in the CustomizeFormatter class's invoke method that I've come unstuck:
class CustomizeFormatter
{
/**
* Customize the given logger instance.
*
* @param \Illuminate\Log\Logger $logger
* @return void
*/
public function __invoke($logger)
{
// What to add here?
}
}
What could be used in there to do what I need?
Is this the wrong path to be taking?
Thanks.
Using the answer found here https://stackoverflow.com/a/34289039/121946 I can add the prefix as extra info at the end of the message using:
public function __invoke($logger)
{
foreach ($logger->getHandlers() as $handler) {
$handler->pushProcessor(function ($record) {
$record['extra']['prefix'] = env('LOG_PREFIX');
return $record;
});
}
}
Looking at the $record, I don't see the full log text, only the custom part:
array:7 [▼
"message" => "Information here..."
"context" => []
"level" => 200
"level_name" => "INFO"
"channel" => "production"
"datetime" => DateTime @1589377784 {#953 ▶}
"extra" => []
]