简体   繁体   English

如何不显示monolog日志行中的最后一个括号?

[英]How not to show last bracket in a monolog log line?

// in my PHP code
$log = new Logger('LaurentCommand');
$log->pushHandler(new StreamHandler('./app/logs/LaurentCommand.log'));
$log->addInfo("Start command",array('username' => 'Joe', 'Age' => '28'));

Result in log file LaurentCommand.log : 结果在日志文件LaurentCommand.log中:

[2012-12-20 10:28:11] LaurentCommand.INFO: Start command {"username":"Joe","Age":"28"} [] [2012-12-20 10:28:11] LaurentCommand.INFO:开始命令{“username”:“Joe”,“Age”:“28”} []

Why this bracket at the end ? 为什么这个支架到底?

That's the extra data. 这是额外的数据。 The default format of the LineFormatter is "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\\n" . LineFormatter的默认格式为"[%datetime%] %channel%.%level_name%: %message% %context% %extra%\\n" the username/age is the context, and extra that is typically empty results in this empty array [] . 用户名/年龄是上下文,而额外的通常是空的结果是这个空数组[]

If you use processors to attach data to log records they typically write it to the extra key to avoid conflicts with context info. 如果使用处理器将数据附加到日志记录,则通常将其写入额外的密钥以避免与上下文信息冲突。 If it really is an issue for you you can change the default format and omit %extra% . 如果它确实是您的问题,您可以更改默认格式并省略%extra%

Edit: As of Monolog 1.11 the LineFormatter has a $ignoreEmptyContextAndExtra parameter in the constructor that lets you remove these, so you can use this: 编辑:从Monolog 1.11开始,LineFormatter在构造函数中有一个$ ignoreEmptyContextAndExtra参数,允许您删除这些参数,因此您可以使用:

// the last "true" here tells it to remove empty []'s
$formatter = new LineFormatter(null, null, false, true);
$handler->setFormatter($formatter);

Old question, but throwing out another simple option: 老问题,但抛出另一个简单的选择:

$slackHandler = new \Monolog\Handler\SlackWebhookHandler(...);
$slackHandler->getFormatter()->ignoreEmptyContextAndExtra(true);

I know this is an old question, but I ran into it too and I want to share my solution. 我知道这是一个老问题,但我也碰到了它,我想分享我的解决方案。

The brackets at the end of log lines are due to how Monolog's LineFormatter tries to json_encode() the data in %extra% . 日志行末尾的括号是由于LineFormatterLineFormatter如何尝试json_encode() %extra%的数据。 The brackets are a JSON representation of an empty array. 括号是空数组的JSON表示。

To turn off those brackets, I ended up having to subclass Monolog\\Formatter\\LineFormatter with my own class and overwrite its convertToString($data) function so it returns an empty string if there's no data present. 为了关闭这些括号,我最终不得不将Monolog\\Formatter\\LineFormatter子类Monolog\\Formatter\\LineFormatter我自己的类并覆盖其convertToString($data)函数,因此如果没有数据,它将返回一个空字符串。 Here's my new subclass: 这是我的新子类:

namespace My\Fancy\Monolog;
use Monolog\Formatter\LineFormatter;

class LineFormatter extends LineFormatter {

    protected function convertToString($data)
    {
        if (null === $data || is_scalar($data)) {
            return (string) $data;
        }

        // BEGIN CUSTOM CODE - This section added to prevent empty 
        // brackets from appearing at the end of log lines:
        if ((is_array($data) && !$data) 
            || is_object($data) && !get_object_vars($data)) {
            return '';
        }
        // END CUSTOM CODE 

        $data = $this->normalize($data);
        if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
            return $this->toJson($data);
        }

        return str_replace('\\/', '/', json_encode($data));
    }
}

You can use this class by injecting an instance of it into your Monolog handler class, like so: 您可以通过将其实例注入Monolog处理程序类来使用此类,如下所示:

$handler = new Monolog\Handler\StreamHandler('/path/to/my/logfile', 'debug');
$handler->setFormatter(new My\Fancy\Monolog\LineFormatter());
$monolog->pushHandler($handler);

Enjoy! 请享用!

Symfony 4 solution: Symfony 4解决方案:

  1. Create logger: 创建记录器:

     use Monolog\\Formatter\\LineFormatter; class Formatter extends LineFormatter { public function __construct( $format = null, $dateFormat = null, $allowInlineLineBreaks = false, $ignoreEmptyContextAndExtra = false ) { parent::__construct($format, $dateFormat, $allowInlineLineBreaks, true); } } 
  2. Define formatter in services.yml : services.yml定义formatter:

     log.custom.formatter: class: App\\Formatter 
  3. Define formatter in monolog.yml for needed environment(s): monolog.yml为所需环境定义格式化程序:

     handlers: main: type: stream path: "%kernel.logs_dir%/%kernel.environment%.log" level: debug channels: ["!event"] formatter: log.custom.formatter 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM