How can I change localhost.localdomain in the messages written by Log4j to the Linux syslog

别等时光非礼了梦想. 提交于 2019-12-21 02:55:24

问题


I'm writing messages to the Linux syslog using Log4j and its SyslogAppender. The outputted messages look like this:

Oct 12 09:06:03 localhost.localdomain 3364 [Thread-5] INFO TEST MESSAGE MyApplicationLogger - This is my message

I would like to replace localhost.localdomain with the name of the server running the application but can't seem to figure out how. Here's my configuration file, in case it's useful:

log4j.logger.MyApplicationLogger=INFO, SyslogAppender
log4j.appender.SyslogAppender=org.apache.log4j.net.SyslogAppender
log4j.appender.SyslogAppender.syslogHost=localhost
log4j.appender.SyslogAppender.Facility=USER
log4j.appender.SyslogAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.SyslogAppender.layout.ConversionPattern= %-4r [%t] %-5p %c %x - %m%n
log4j.appender.SyslogAppender.source=My Application

Edit: the computer name is configured on the server and the hostname command returns the following:

$ hostname
server12

I do notice however that the first line of the hosts file is

127.0.0.1   localhost.localdomain localhost

However I'm hesitant to change this.


回答1:


This is what you need:

log4j.appender.SyslogAppender.header = true



回答2:


This issue is because your machine doesn't know it's own host name. This can be demonstrated by running the command hostname as a non-privileged user.

If you have root privileges then you can set your host name using

$ hostname myServersHostname

man page

To make this change permanent across reboots you will need to set a configuration file somewhere in /etc (exactly which one depends on your distro).

  • Debian/ubuntu: /etc/hostname
  • Redhat/CentOS/Fedora: /etc/sysconfig/network



回答3:


I figured out how to fix it, so I might as well leave the solution here in case other people face the same problem.

In the properties file, put this:

log4j.appender.SyslogAppender.syslogHost=server12

Not sure why it works, but using the server name instead of localhost worked for me.




回答4:


If you don't want to 'hard code' the hostname in the log4j properties or XML file, the best solution is a combination of what is suggested by dtyler and yegor256. Make sure your hostname is set correctly, and then use log4j.appender.SyslogAppender.header = true or <param name="Header" value="true"/> in your log4j.xml



来源:https://stackoverflow.com/questions/7744840/how-can-i-change-localhost-localdomain-in-the-messages-written-by-log4j-to-the-l

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!