扩展 Laravel 日志前缀以包含自定义环境变量

Extend Laravel log prefix to include custom environment variable

对于 Laravel 5.7 应用程序,我想在默认日志前缀中添加一些额外的信息。

日志条目当前如下所示:

[2020-05-13 13:07:42] production.INFO: Information here...

我想扩展前缀使其成为:

[2020-05-13 13:07:42] PREFIX.production.INFO: Information here...

PREFIX 来自环境变量,LOG_PREFIX:

LOG_CHANNEL=daily
LOG_PREFIX=PREFIX

我不介意使用正则表达式将 production.INFO 更改为 PREFIX。production.INFO 在自定义格式化程序中。

我在日志频道添加了点击:

'daily' => [
    'driver' => 'daily',
    'path' => storage_path('logs/laravel.log'),
    'level' => 'debug',
    'days' => 7,
    'tap' => [App\Logging\CustomizeFormatter::class],
]

我在 CustomizeFormatter class 的调用方法中遇到了问题:

class CustomizeFormatter
{
    /**
     * Customize the given logger instance.
     *
     * @param  \Illuminate\Log\Logger  $logger
     * @return void
     */
    public function __invoke($logger)
    {
        // What to add here?
    }
}

里面有什么可以满足我的需要?

这条路走错了吗?

谢谢。

使用此处找到的答案 我可以使用以下方法在消息末尾添加前缀作为额外信息:

public function __invoke($logger)
{
    foreach ($logger->getHandlers() as $handler) {
      $handler->pushProcessor(function ($record) {
          $record['extra']['prefix'] = env('LOG_PREFIX');
          return $record;
      });
  }
}

查看 $record,我没有看到完整的日志文本,只有自定义部分:

array:7 [▼
  "message" => "Information here..."
  "context" => []
  "level" => 200
  "level_name" => "INFO"
  "channel" => "production"
  "datetime" => DateTime @1589377784 {#953 ▶}
  "extra" => []
]

将其添加到 extras 中不会按照您想要的方式显示,这里是默认的行格式:

[%datetime%] %channel%.%level_name%: %message% %context% %extra%

如您所见,额外内容在最后,因此它会产生如下内容:

[2020-05-13 16:50:20] development.INFO: [] {"prefix":"MyPrefix"}

您可以改为这样做:

<?php

namespace App\Logging;

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

class CustomizeFormatter
{
    /**
     * Customize the given logger instance.
     *
     * @param  Logger  $logger
     *
     * @return void
     */
    public function __invoke($logger)
    {
        foreach ($logger->getHandlers() as $handler) {
            $handler->pushProcessor(function ($record) {
                return Arr::add($record, 'prefix', env('LOG_PREFIX'));
            });
            $handler->setFormatter(tap(new LineFormatter(
                "[%datetime%] %prefix%.%channel%.%level_name%: %message% %context% %extra%\n",
                'Y-m-d H:i:s',
                true,
                true
            ), function ($formatter) {
                $formatter->includeStacktraces();
            }));
        }
    }
}

这将产生以下结果:

[2020-05-13 16:52:24] MyPrefix.development.INFO: []  

我们在这里做的是添加一个新的处理器并向其添加密钥 prefix。 然后我们可以在行格式器上使用这个键,并能够决定我们想要用 %prefix%

显示它的位置