如何在Laravel中将数据添加到所有日志记录? [英] How to add data to all log records in Laravel?

查看:246
本文介绍了如何在Laravel中将数据添加到所有日志记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to add some data to all log records within my Laravel application.

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

I think it would be helpful to know the username of the current user and/or the client IP address.

目前,我正在通过以下方式手动添加它:

Currently I'm adding it manually by doing:

Log::info('Pre-paid activation.', array('username' => Auth::user()->username));

但是我想知道如何添加侦听器或使所有日志记录具有用户名(如果可用)的东西.

But I would like to know how to do add a listener or something to make all log recorde have the username (if available).

推荐答案

自从Laravel开箱即用 Monolog ,这很简单.通过编辑app/start/global.php并在以Log::useFiles:

Since Laravel comes out of box with Monolog, it is pretty straight forward. It can be easily achieved by editing app/start/global.php and add the following after the line that starts with: 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;
});

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

Basically, we are using the underlying Monolog instance to register a processor which will intercept any log record to be written. The results will be similar as the followings:

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

[2014-04-12 23:07:35] local.INFO: Pre-paid activation. [] {"user":"anonymous","ip":"::1"}

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

More information about Monolog processors: https://github.com/Seldaek/monolog/blob/master/doc/01-usage.md#using-processors

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

Extra: The hardcoded extra is to tell Monolog to add data as extra piece of information (redundant to say). In the practice, this is to avoid overriding any context data added in the original log call.

这篇关于如何在Laravel中将数据添加到所有日志记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆