Malvin
Malvin

Reputation: 859

How to configure log4j fileappender for all classes?

In my application I read in an inputfile (e.g. myFile1.txt) and create an outputfile with the same name (e.g. myFile2log). Point is that the inputfile will be read within the java application and not given as command line parameter. Therefore it is required to set an appender in the application, e.g.

public class Example {
private static final Logger LOG = Logger.getLogger(Example.class);

public Example() throws IOException {
    FileAppender appender = new DailyRollingFileAppender(new PatternLayout(
            PatternLayout.DEFAULT_CONVERSION_PATTERN), "yourfilename.log",
            "'.'yyyy-MM-dd");
    LOG.addAppender(appender);
    LOG.setLevel((Level) Level.DEBUG);
    LOG.debug("blabla");

    new RandomClass();
}

public static void main(String[] args) throws IOException {
    new Example();
}
}

public class RandomClass {
private static final Logger LOG = Logger.getLogger(RandomClass.class);

public RandomClass() {
    LOG.debug("hello Randomclass");
}
}

And here is the problem: if I do the above the custom file appender only works for the specific class where the fileappender was defined, but not on any other class. Therefore the output of the "RandomClass" will not be written into this logfile, but which is what is required. How can I achieve that?

Upvotes: 0

Views: 4644

Answers (2)

dan
dan

Reputation: 13272

If you would like to set the appender dynamically you should try setting the new appender to the root logger:

Logger logger = Logger.getRootLogger();
FileAppender appender = new DailyRollingFileAppender(new PatternLayout(
   PatternLayout.DEFAULT_CONVERSION_PATTERN), "yourfilename.log", "'.'yyyy-MM-dd");
logger.addAppender(appender)

Upvotes: 1

vels4j
vels4j

Reputation: 11298

You can use log4j.properties file in your class path then simply you can initilize logger in all the classes.

private static final Logger LOG = Logger.getLogger(Example.class);

and Appender all not required in constructor. your property file should contain

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=yourfilename.log
log4j.appender.R.MaxFileSize=2048KB

Upvotes: 1

Related Questions