hostname in file created by log4j
I'm using java 1.4.2 on Linux machine (RHEL 5.4).
Our application uses log4j for logging. I want that some appender will create files containing hostname in file name. Hostname should not be hardocoded, but rather use system properties similar to here (see ${log4j.minutes}).
So the question is if there's hostname in system properties. According 开发者_如何学Pythonto here, there's no default hostname property.
This means I need to add hostname as system property from code of from command line (-D flag).
Do I miss something?
No. There is no default hostname in the system properties. Also a computer may have multiple netcards, and each netcard may have several IP-numbers allocated and each IP-number may have its own name, so there might be several candidates for what the "default hostname" might be.
When you have extracted the hostname you like, then look into how you can save it in the log4j MDC - which is a Map in disguise - so you can refer to in your logging string in your configuration).
Another option in a linux environment is to use the SyslogAppender, which includes the host in the output, and allows you benefits like centralized log aggregation. You need to set the header attribute to true to enable the timestamp and host to be sent in standard syslog convention. If you do, then you get output like this, where xenon is the hostname of the machine:
Apr 25 14:33:17 xenon INFO Some log message
In this example the conversion pattern is %-5p %c{2} - %m%n
I think you'll have to extend FileAppender and override activateOptions() to set fileName property to a desired value. Read the host name from some property or get it from InetAddress.getLocalHost().getHostName().
精彩评论