【问题标题】:SyslogAppender: Using a pattern not starting with square brackets overwrites the host nameSyslogAppender:使用不以方括号开头的模式会覆盖主机名
【发布时间】:2015-05-10 01:05:46
【问题描述】:

我正在使用 log4j 和 SyslogAppender 类将消息发送到在本地 Linux 机器(称为 orion)上运行的 rsyslog。我目前有以下模式:

log4j.appender.SYSLOG_LOCAL1.layout.conversionPattern=[%p] %m%n

产生这个输出:

Jun  5 16:16:09 orion [ERROR]: <My message here>

这没有显示消息的来源,所以我想添加它,但不幸的是,当我在方括号前添加任何内容时,主机名消失了。例如。

log4j.appender.SYSLOG_LOCAL1.layout.conversionPattern=TEST [%p] %m%n

Jun  5 16:22:41 TEST [ERROR]: <My message here>

导致这个问题的不仅仅是文字。例如,如果我使用来自documentation 的示例模式,"%-5p [%t]: %m%n",主机名也不存在:

log4j.appender.SYSLOG_LOCAL1.layout.conversionPattern=%-5p [%t]: %m%n

Jun  5 16:25:34 ERROR [main]: <My message here>

这是我能想出的最简单的例子来演示使用模式aaa[aaa] 的问题:

log4j.appender.SYSLOG_LOCAL1.layout.conversionPattern=aaa
Jun  5 17:47:29 aaa

log4j.appender.SYSLOG_LOCAL1.layout.conversionPattern=[aaa]
Jun  5 17:48:24 orion [aaa]:

文档没有显示方括号有任何特殊含义,所以我不明白为什么会这样。我也不清楚这个问题是由 SyslogAppender 类还是 rsyslog 引起的。

如何在系统日志消息中保留主机名而不用方括号括起第一项?

【问题讨论】:

  • 您找到解决方案了吗? :)
  • 很遗憾我没有。
  • @guitar_freak 我有,现在。

标签: java log4j rsyslog


【解决方案1】:

我决定通过查看 SyslogAppender 类的 the source 以全新的眼光看待这个问题。

这个子类有一个名为header的额外字段:

  105       /**
  106        * If true, the appender will generate the HEADER (timestamp and host name)
  107        * part of the syslog packet.
  108        * @since 1.2.15
  109        */
  110     private boolean header = false;

将此值设置为 true 允许显示主机名。

log4j.appender.SYSLOG_LOCAL1.layout.conversionPattern=TEST [%p] %m%n

May  9 16:50:14 orion TEST [ERROR] <my message here>

setHeader() 的文档(与getHeader() 的文档混淆)包含一些关于默认值的额外信息。

  460     /**
  461      * If true, the appender will generate the HEADER part (that is, timestamp and host name)
  462      * of the syslog packet.  Default value is false for compatibility with existing behavior,
  463      * however should be true unless there is a specific justification.
  464      * @since 1.2.15
  465     */
  466     public final boolean getHeader() {
  467         return header;
  468     }
  469   
  470       /**
  471        * Returns whether the appender produces the HEADER part (that is, timestamp and host name)
  472        * of the syslog packet.
  473        * @since 1.2.15
  474       */
  475     public final void setHeader(final boolean val) {
  476         header = val;
  477     }

header 值可以通过调用setHeader(true) 在 Java 代码中设置,也可以在 log4j.properties 中添加以下行:

log4j.appender.SYSLOG_LOCAL1.header=true

SYSLOG_LOCAL1 替换为您在属性文件中命名此附加程序的任何名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多