dushkin
dushkin

Reputation: 2101

How to add the current client directory to the log file name?

I've been struggling with this problem in subject.

I tried something like this:

String sCurrDir = System.getProperty("user.dir");
int nLastBSlash = sCurrDir.lastIndexOf('/');
System.setProperty("current.folder", sCurrDir.substring(nLastBSlash + 1));

and added the following to the log4j.properties:

<appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
  <param name="Threshold" value="DEBUG" />
  <param name="append" value="true" />
  <param name="maxFileSize" value="10MB" />
  <param name="maxBackupIndex" value="50" />

  <param name="File" value="./log/${current.folder}-wcss-simulator-${current.date}.log"/>

  <layout class="org.apache.log4j.PatternLayout">
     <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss,SSS}\t %-5p\t [%X{ThreadId}]\t %X{MethodName}\t - %m%n" />
  </layout>
</appender>

But the file name only starts with an hyphen.

Upvotes: 1

Views: 632

Answers (2)

PentaKon
PentaKon

Reputation: 4636

Your implementation doesn't work because logging has already started before you set the current.folder property. Do you have access to the program's main method or is this a container based application?

If you have access to the main method you have to make sure the first thing you do is set that property, before creating the first Logger instance.

Upvotes: 1

kk.
kk.

Reputation: 3945

You can try implementing your own Appender like:

import org.apache.log4j.RollingFileAppender;    
public class CustomFileAppender extends RollingFileAppender {

        public CustomFileAppender() {
            super();
            String sCurrDir = System.getProperty("user.dir");
            int nLastBSlash = sCurrDir.lastIndexOf('/');
            System.setProperty("current.folder", sCurrDir.substring(nLastBSlash + 1));
        }
    }

Configure log4j properties/xml file as:

<appender name="fileAppender" class="CustomFileAppender">
      <param name="Threshold" value="DEBUG" />
      <param name="append" value="true" />
      <param name="maxFileSize" value="10MB" />
      <param name="maxBackupIndex" value="50" />

      <param name="File" value="./log/${current.folder}-wcss-simulator-${current.date}.log"/>

      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss,SSS}\t %-5p\t [%X{ThreadId}]\t %X{MethodName}\t - %m%n" />
      </layout>
   </appender>

Upvotes: 0

Related Questions