3

We are using Log4j for logging in our web application. Our applications are deployed in Websphere cluster environment.

For example:

There is one Host having two different JVMs where web applications are deployed.

Host-1      
  JVM -1 [App-1, App-2]
  JVM -2 [App-1, App-2]

Log4j configuration for App-1 is:

<log4j:configuration debug="true">
    <appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
        <appender-ref ref="FileOut" />
    </appender>
    <appender name="FileOut" class="org.apache.log4j.RollingFileAppender">
        <param name="File" value="/home/applogs/app-1.log" />
        <param name="DatePattern" value="'.'yyyy-MM-dd" />
        <param name="Append" value="true" />
        <param name="MaxFileSize" value="10MB" />
        <param name="MaxBackupIndex" value="5" />
        <param name="Threshold" value="ALL" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="%d %-5p - %m%n" />
        </layout>
    </appender>   
    <root>
        <level value="INFO" />
        <appender-ref ref="ASYNC" />
    </root>    
</log4j:configuration>

But here the problem is different JVM logs are being written in same file /home/applogs/app-1.log.

Is there any way to configure seperate log files for clustering environment? So that my Log4j configuration should not be updated in case we deploy application in 1 JVM or 2 JVM or 3 JVM or So on?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Narendra Verma
  • 2,372
  • 6
  • 34
  • 61

1 Answers1

0

You can use ManagementFactory.getRuntimeMXBean().getName() to look up the ProcessID of your JVM at Runtime to get a unique fileName, then you need somehow to update the fileName at runtime of your logger. Have a look at this Answer to do this. In complete:

Add to your main-method:

//set a property to the JVM-Name
System.setProperty("logFilename", ManagementFactory.getRuntimeMXBean().getName());
//update the Logger context to relead the filename with the lookup
LoggerContext ctx =  (LoggerContext) LogManager.getContext(false);
ctx.reconfigure();

Use in your log4j2.xml a Appender with a Lookup for the filename:

<appenders>
<File name="MyFile" fileName="${sys:logFilename}.log">
    <PatternLayout pattern="%-4r %d{${datestamp}} [%t] %-5level %logger{36} - %msg%n"/>
</File>
</appenders>
Community
  • 1
  • 1
Simulant
  • 19,190
  • 8
  • 63
  • 98
  • We did it in bit different way, Set the JVM custom property say **"logging.log4j.location=/home/applogs/{WAS_SERVER_NAME}"** and we can use this property in log4j configuration say **** – Narendra Verma Mar 13 '13 at 07:05
  • it would be ${logging.log4j.location} for log4j v1.x - the reference I found to this is in the migration guide https://logging.apache.org/log4j/2.x/manual/migration.html – hello_earth Mar 18 '21 at 15:33