Solved

LOG4J - how to control log file name?

Posted on 2010-09-11
8
2,589 Views
Last Modified: 2012-05-10
Hi.

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:
  monitor-20100910-492.log
  executor-20100910-1231.log
  executor-20100910-3786.log
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 log4j.properties enclosed.

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

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.conversionPattern=%d{ABSOLUTE} %m%n

log4j.appender.monitorLog=org.apache.log4j.FileAppender
log4j.appender.monitorLog.file=${user.dir}/logs/monitor.log
log4j.appender.monitorLog.layout=org.apache.log4j.PatternLayout
log4j.appender.monitorLog.layout.conversionPattern=%d{ABSOLUTE} %m%n

log4j.appender.executorLog=org.apache.log4j.FileAppender
log4j.appender.executorLog.file=${user.dir}/logs/executor.log
log4j.appender.executorLog.layout=org.apache.log4j.PatternLayout
log4j.appender.executorLog.layout.conversionPattern=%d{ABSOLUTE} %m%n

Open in new window

0
Comment
Question by:Dmitry_Bond
  • 5
  • 2
8 Comments
 
LVL 4

Accepted Solution

by:
denissie earned 500 total points
ID: 33654565
0
 
LVL 4

Expert Comment

by:denissie
ID: 33654571
0
 
LVL 20

Expert Comment

by:Sathish David Kumar N
ID: 33655952
you want to define in rootCategory...
0
ScreenConnect 6.0 Free Trial

Explore all the enhancements in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI, app configurations and chat acknowledgement to improve customer engagement!

 

Author Comment

by:Dmitry_Bond
ID: 33656088
Ok. I have tried to set log file name using the approach described at
    http://cognitivecache.blogspot.com/2008/08/log4j-writing-to-dynamic-log-file-for.html
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?
0
 

Author Comment

by:Dmitry_Bond
ID: 33656095
Btw, may you see something wrong in a code...
@SuppressWarnings("rawtypes")
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";
		fa.setFile(fn);
		//fa.activateOptions();
	}		
}

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

Open in new window

0
 

Author Comment

by:Dmitry_Bond
ID: 33657008
Btw, I found duplicated console messages - it was my mistake. I copied log4j.properties file to project folder, so Eclipse included it into a JAR. So, it seems 2 similar log4j.properties 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 log4j.properties; 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.
0
 

Author Comment

by:Dmitry_Bond
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
  http://stackoverflow.com/questions/192456/setting-a-log-file-name-to-include-current-date-in-log4j

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());
            makeDirs(actualFileName);
            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!

log4j-all.xml
0
 

Author Closing Comment

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

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
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 scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

777 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