How to inject customized info to Google Stackdriver in Laravel log

861 Views Asked by At

Hi I'm new to Laravel framework and I'm trying to inject process ID into every log passed to Google Logging service.

I've been able to see the log passed into Google Logging service now, but I've no idea how I could inject more info(Process ID in this case) into my log message.

So far I've tried "tap" method and I can see addition info injected into my log while reading laravel.log file, but same method doesn't seems to work while using Google Cloud Logging plugin.

Below is my script for Google Logging service.

Inside config/logging.php

'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => ['stackdriver'],
        ],
        'stackdriver' => [
            'driver' => 'custom',
            'via' => App\Logging\CreateStackdriverLogger::class,
            'level' => 'debug',
        ],
        'single' => [
            'driver' => 'single',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
            'tap' => [App\Logging\ProcessorTap::class],
        ],
];

CreateStackdriverLogger.php


use Google\Cloud\Logging\LoggingClient;
use Monolog\Handler\PsrHandler;
use Monolog\Logger;

class CreateStackdriverLogger
{
    /**
     * Create a custom Monolog instance.
     *
     * @param  array  $config
     * @return \Monolog\Logger
     */
    public function __invoke(array $config)
    {

        $logName = isset($config['logName']) ? $config['logName'] : 'app';
        $psrLogger = LoggingClient::psrBatchLogger($logName);
        $handler = new PsrHandler($psrLogger);
        $logger = new Logger($logName, [$handler]);

        return $logger;
    }
}

Code for 'tap' method, I'm able to see 'pid' inside 'extra', but same method don't work with 'stackdriver'.

ProcessorTab.php

namespace App\Logging;

use Illuminate\Log\Logger;
use Illuminate\Support\Arr;
use Monolog\Formatter\LineFormatter;

class ProcessorTap
{

    public function __invoke($logger)
    {
        foreach ($logger->getHandlers() as $handler) {
            $handler->pushProcessor(function ($record) {
                return Arr::add($record, 'prefix', getmypid());
            });
            $handler->setFormatter($this->getLogFormatter());

            $handler->pushProcessor([$this, 'processLogRecord']);
        }
    }

    public function processLogRecord(array $record): array
    {
        $record['extra'] += [
            'pid' => getmypid(),
        ];

        return $record;
    }
    
    protected function getLogFormatter()
    {        
        $format = "[%datetime%] %channel%.%level_name%: %prefix%.%message% %context% %extra%\n";
        return new LineFormatter($format, null, true, true);
    }    

}
0

There are 0 best solutions below