LOG4J - how to control log file name?

Posted on 2010-09-11
Last Modified: 2012-05-10

My Java application create a number of instances of the same application (let say - executor).
But I need that different instances of the same application writes different log files.

Another important thing I need is - all such log files should have log filename containing the current date in a format - YYYYMMDD and ProcessID of the process which writing this log file.
So, finally I expect following files on a disk:
and so on.

Could you please give me some hints/ideas how can I do this with LOG4J (v1.2.16)?

Btw, please see the example of my enclosed.

log4j.logger.Monitor=TRACE, monitorLog, stdout
log4j.logger.Executor=TRACE, executorLog
log4j.logger.bto.utils.ThreadPool=WARN, threadPool

log4j.appender.stdout.layout.conversionPattern=%d{ABSOLUTE} %m%n

log4j.appender.monitorLog.layout.conversionPattern=%d{ABSOLUTE} %m%n

log4j.appender.executorLog.layout.conversionPattern=%d{ABSOLUTE} %m%n

Open in new window

Question by:Dmitry_Bond
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 2

Accepted Solution

denissie earned 500 total points
ID: 33654565

Expert Comment

ID: 33654571
LVL 20

Expert Comment

by:Sathish David Kumar N
ID: 33655952
you want to define in rootCategory...
[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.


Author Comment

ID: 33656088
Ok. I have tried to set log file name using the approach described at
But unfortunately it makes all messages on console duplicated! :-(((
But why?!
Messages in a log file are not duplicated, only in console.
Looks completely weird!
Any ideas what could be wrong with it?

Author Comment

ID: 33656095
Btw, may you see something wrong in a code...
public static Appender findLogAppender(String pLogName, Class pLogAppenderClass)
	Logger log = Logger.getLogger(pLogName);
	Enumeration appenders = log.getAllAppenders();
	while (appenders.hasMoreElements())
		Appender currAppender = (Appender)appenders.nextElement();
		if (pLogAppenderClass.isInstance(currAppender))
			return currAppender;
	return null;

public static void setLogFilename(String pLogName)
	Object logAppender = MiscUtils.findLogAppender(pLogName, org.apache.log4j.FileAppender.class);
	if (logAppender != null)
		FileAppender fa = (FileAppender)logAppender;
		String fn = fa.getFile();			
		String fp = includeTrailing(exctractFilePath(fn), File.separatorChar);
		fn = MiscUtils.exctractFileNameNoExt(fn);
		fn = fp + fn + "-" + MiscUtils.getDateStamp('\0') + ".log";

// then init 2 loggers:
setLogFilename("Monitor"); // in main application
setLogFilename("Executor"); // in executor application

Open in new window


Author Comment

ID: 33657008
Btw, I found duplicated console messages - it was my mistake. I copied file to project folder, so Eclipse included it into a JAR. So, it seems 2 similar files (one in JAR), second in directory with JAR caused console messages duplicated. As for me it looks like a bug in LOG4J - I believe it should not take into account duplicated; assume same names and same properties for logger should not create duplicated objects.

Ok. But my question is - what can i do with the empty log files (monitor.log and executor.log) which was created on application start. Looks like LOG4J initialize and create default log files before I set log filenames. Is there any way to avoid it? I mean - standard way. Prefer to avoid coding custom functionality if possible.

Author Comment

ID: 33657883
Ok... Seems I have solved all logging problems.
Not the way I like but at least it working fine.

So, took the code from

Change the "setFile" method to

      public synchronized void setFile(String fileName, boolean append,
                  boolean bufferedIO, int bufferSize) throws IOException
            SimpleDateFormat sdf = new SimpleDateFormat(fileBackup);
            String actualFileName = sdf.format(new Date());
            actualFileName = actualFileName.replaceAll("\\$PID", MiscUtils.getPID());
            super.setFile(actualFileName, append, bufferedIO, bufferSize);

Implemented "getPID()" method as

      public static String getPID()
            String pid = ManagementFactory.getRuntimeMXBean().getName();
            int p = pid.indexOf('@');
            if (p >= 0)
                  pid = pid.substring(0, p);
            return pid;

Then split log4j.xml config file to 2 separate files - log4j-mon.xml (for monitor app) and log4j-exec.xml (for executor app).

Then adjusted command line which starts monitor application and command line which starts executor application:

java.exe -Dlog4j.configuration=log4j-mon.xml Monitor
java.exe -Dlog4j.configuration=log4j-exec.xml MonExecutor

So, seems now everything is working fine. No dummy files, no duplicated messages.

Thank you very much for help!


Author Closing Comment

ID: 33657895
After some experiments and adjustments I finally make solution working. Thanks.

Featured Post

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Suggested Courses

626 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question