How to append hostname to log file in log4j.xml

Prasanna Kumar H A picture Prasanna Kumar H A · Mar 23, 2016 · Viewed 27.3k times · Source

I want to append hostname and date to log file name.So log file Name should be like app_hostname.date.log. Note: This should run in both linux and windows.

<appender name="applog" class="org.apache.log4j.DailyRollingFileAppender">
        <param name="File" value="${path}/app.log" />
        <param name="MaxFileSize" value="1MB" />
        <param name="DatePattern" value=".dd-MM-yyyy" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%d{dd-MM-yyyy HH:mm:ss}] [%-5p] %m%n"/>
        </layout>
</appender>

And how to add filter based on the log pattern, not as StringMatchFilter.I want pattern to be matched. Thanks in advance

Answer

Jose Duarte picture Jose Duarte · Sep 14, 2016

Following the log4j2 documentation you can do environment variable lookups, so in Unix-like systems this should work:

<Property name="MYHOST">${env:HOSTNAME}</Property>
<Appenders>
  <File name="File1" fileName="${MYHOST}_file.log">
  ...
  </File>
</Appenders>

Beware that $HOSTNAME is not always available by default and you might need to export it explicitly in the shell, see this post.