How to append hostname to log file in log4j.xml

Viewed 34611

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

8 Answers

I found that just ${hostName} by default would work for latest log4j

Something like this:

    <File name="file" fileName="${baseDir}/${hostName}-file.log" append="true">

This is documented under here: https://logging.apache.org/log4j/2.x/manual/configuration.html#AutomaticConfiguration

In the Default Properites Section:

The default map is pre-populated with a value for "hostName" that is the current system's host name or IP address

try this : "${env:HOST}-${date:yyyy-MM-dd}" Hostname + Date . In yaml:

Properties:
    Property:
      - name: log-path
        value:  "logs"
      - name: filePattern
        value:  "${env:HOST}-${date:yyyy-MM-dd}"

  Appenders:

    Console:
      name: Console_Appender
      target: SYSTEM_OUT
      PatternLayout:
        pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"

    File:
      name: File_Appender
      fileName: "${log-path}/filelog-${filePattern}.log"
Related