2

We have a requirement in the application that the log file created shoud have a different name every time it executes (based on functionality + the current thread). I have seen the questions already posted in SO and tried to use the same method, but it is not working.

All the log statements are getting logged in "xyz.log" (specified in the log4j.properties). Only "org.apache.log4j.PatternLayout" gets logged in abc.log (specified in the program). Any pointers to solve this will be very helpful.

log4j.properties

log4j.rootLogger=DEBUG, MyLogger

log4j.appender.MyLogger=org.apache.log4j.FileAppender
log4j.appender.MyLogger.layout=org.apache.log4j.PatternLayout

log4j.appender.MyLogger = org.apache.log4j.DailyRollingFileAppender
log4j.additivity = false
log4j.appender.MyLogger.File=xyz.log
log4j.appender.MyLogger.MaxFileSize = 5MB
log4j.appender.MyLogger.MaxBackupIndex = 20
# Pattern to output the caller's file name and line number.
log4j.appender.MyLogger.layout.ConversionPattern=%d %5p [%t](%c:%L) - %m%n

Java code

    logger = Logger.getLogger(MyLoggerUtil.class);
    Layout layout = new PatternLayout("org.apache.log4j.PatternLayout");
    logger.removeAllAppenders();
    FileAppender appender = null;
    try {
        appender = new FileAppender(layout, "abc.log", false);
    } catch (IOException e) {
        e.printStackTrace();
    }
    logger.addAppender(appender);
    logger.setLevel((Level) Level.DEBUG);
    logger.debug("This is a debug test");
2
  • 1
    The constructor of PatternLayout expects a pattern not a class name. Sth. like the conversion pattern you used in the properties file. Commented Feb 28, 2012 at 8:01
  • Good to hear. I created an answer for this. Commented Feb 28, 2012 at 8:54

1 Answer 1

1

The constructor of PatternLayout expects a conversion pattern, like the one used in the lo4j.properties. So change the creation of the Layout to:

Layout layout = new PatternLayout("%d %5p [%t](%c:%L) - %m%n");

Pattern taken from your log4j.properties

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.