如何在Laravel日志中向Google Stackdriver注入自定义信息

问题描述

嗨,我是Laravel框架的新手,我正在尝试将进程ID注入传递给Google Logging服务的每个日志中。

我现在已经可以看到将日志传递到Google Logging服务中,但是我不知道如何向日志消息中注入更多信息(在这种情况下为Process ID)。

到目前为止,我已经尝试了“ tap”方法,并且在读取laravel.log文件时可以看到其他信息注入了日志,但是在使用Google Cloud Logging插件时,该方法似乎不起作用。

下面是我的Google Logging服务脚本。

内部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'),'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;
    }
}

“ tap”方法代码,我可以在“ extra”中看到“ pid”,但是相同的方法不适用于“ 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);
    }    

}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)