如何将数据添加到Laravel中的所有日志记录?

Rub*_*zzo 5 laravel monolog laravel-4

我想在Laravel应用程序中的所有日志记录中添加一些数据.

我认为了解当前用户的用户名和/或客户端IP地址会很有帮助.

目前我正在手动添加它:

Log::info('Pre-paid activation.', array('username' => Auth::user()->username));
Run Code Online (Sandbox Code Playgroud)

但我想知道如何添加一个监听器或其他东西,以使所有日志记录具有用户名(如果可用).

Rub*_*zzo 10

由于Laravel出来与盒子的独白,这是很简单的.通过编辑app/start/global.php并在以下开头的行之后添加以下内容,可以轻松实现Log::useFiles:

Log::useFiles(storage_path().'/logs/laravel.log');
$monolog = Log::getMonolog();
$monolog->pushProcessor(function ($record) {
    $record['extra']['user'] = Auth::user() ? Auth::user()->username : 'anonymous';
    $record['extra']['ip'] = Request::getClientIp();
    return $record;
});
Run Code Online (Sandbox Code Playgroud)

基本上,我们使用底层的Monolog实例来注册一个处理器,该处理器将拦截要写入的任何日志记录.结果将类似如下:

[2014-04-12 23:07:35] local.INFO:预付费激活.[] {"user":"anonymous","ip":":: 1"}

有关Monolog处理器的更多信息:https://github.com/Seldaek/monolog/blob/master/doc/01-usage.md#using-processors


额外:硬编码extra是告诉Monolog将数据添加为额外的信息(多余的说).在实践中,这是为了避免覆盖原始日志调用中添加的任何上下文数据.

  • 对于Laravel 5,只需创建LogServiceProvider,将其添加到config/app.php,并将相同的$ monolog代码添加到boot()方法中. (5认同)

Fin*_*sse 10

在 Laravel 5 中,您可以通过自定义 Monolog 来实现。首先创建一个自定义 Monolog 的类,以便将用户信息添加到日志记录中:

namespace App\Logging;

use App\Models\User;
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Log\Logger;

class AddUserInformation
{
    protected $request;

    public function __construct(Request $request = null)
    {
        $this->request = $request;
    }

    public function __invoke(Logger $logger)
    {
        if ($this->request) {
            foreach ($logger->getHandlers() as $handler) {
                $handler->pushProcessor([$this, 'processLogRecord']);
            }
        }
    }

    public function processLogRecord(array $record): array
    {
        $record['extra'] += [
            'user' => $this->request->user()->username ?? 'guest',
            'ip' => $this->request->getClientIp()
        ];

        return $record;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后通过将类添加到config/logging.php文件中的通道设置来将类连接到 Laravel 记录器:

// ...
'channels' => [
    'single' => [
        'driver' => 'single',
        'tap' => [\App\Logging\AddUserInformation::class],
        'path' => storage_path('logs/laravel.log'),
        'level' => env('LOG_LEVEL', 'debug'),
    ],
    // ...
]
Run Code Online (Sandbox Code Playgroud)

关于自定义 Monolog 的文档