Format Laravel log messages for Papertrail

You can edit the information that is in your log messages when Laravel writes to the log.

I wanted to add the application name to the log messages.

// in config/logging.php
...

        'papertrail' => [
            'driver' => 'monolog',
            'level' => env('LOG_LEVEL', 'debug'),
            'handler' => SyslogUdpHandler::class,
            'handler_with' => [
                'host' => env('PAPERTRAIL_URL'),
                'port' => env('PAPERTRAIL_PORT'),
            ],
            'tap' => [App\Logging\CustomizeLogFormatter::class],
        ],
...

Then create a new file ./app/Logging/CustomizeLogFormatter.php

<?php

// file ./app/Logging/CustomizeLogFormatter.php
declare(strict_types=1);

namespace App\Logging;

use Monolog\Formatter\LineFormatter;

class CustomizeLogFormatter
{
    public function __invoke($logger): void
    {
        foreach ($logger->getHandlers() as $handler) {
            $handler->setFormatter(new LineFormatter(
                '%channel%.%level_name%: '.config('app.name').': %message% %context% %extra%\n'
            ));
        }
    }
}

Click Here to Leave a Comment Below

Leave a Reply: