6

I'm trying to append the current date to the log4j log file. So it would be something like this:

myApp-2011-01-07.log

The thing is that I do not want to use the DailyRollingFileAppender. Reason is that there will be another script that runs daily that will backup everything in the logs folder. This is running under Tomcat5.5.

Is this possible in log4j?

Marquinio
  • 4,601
  • 13
  • 45
  • 68

3 Answers3

14

I think you could just set a system property in code to contain the current date:

static{
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    System.setProperty("current.date", dateFormat.format(new Date()));
}

Then in your log4j.xml file you can use the system property when specifying the log file name in the appender:

<appender name="MYAPPENDER" class="org.apache.log4j.FileAppender">
    <param name="File" value="${user.home}/myApp-${current.date}.log" />

ETA: Now that I think about it you may have to setup the system property using a static initializer to make sure the property is set before log4j is configured.

BenjaminLinus
  • 2,100
  • 23
  • 24
  • will it create a new file for new date and day? or it will create just once? – Steve Feb 27 '15 at 15:45
  • Its been awhile since I have looked at log4j but I think the example I gave would create just one log file for the day you started your process. Use a "RollingFileAppender" in your log4j.xml if you wanted a new log file every day. – BenjaminLinus Feb 27 '15 at 19:59
11

you can manage this quickly and highly mantainable by just creating your own Appender.

Just create a Class like this :

    import java.text.SimpleDateFormat;
    import java.util.Date;
    import org.apache.log4j.FileAppender;

    public class CustomFileAppender extends  FileAppender{

    @Override
    public void setFile(String fileName)
    {
        if (fileName.indexOf("%timestamp") >= 0) {
            Date d = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSS");
            fileName = fileName.replaceAll("%timestamp", format.format(d));
        }
        super.setFile(fileName);
   }
}

and place this in your properties:

   log4j.appender.file=com.portima.filenet.brio.ops.tools.CustomFileAppender
   log4j.appender.file.File=${log}/general.%timestamp.log

Now you can give any type of filename you want.

Yoeri Smets
  • 142
  • 1
  • 9
5

Try setting this in your log4j.properties file:

log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=example.log

much more information can be found here http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/DailyRollingFileAppender.html

Simulant
  • 19,190
  • 8
  • 63
  • 98
Ratna Dinakar
  • 1,573
  • 13
  • 16
  • So, if I set my log to rotate at midnight, what happens to the older log files? Each log file has a file date stamp on it, so I am worried that I will have log files that will be months old in the directory. – Sun Dec 20 '12 at 17:13