0

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?

Malvin
  • 859
  • 2
  • 11
  • 19
  • Can you not use a log4j.properties file alongside your application to specify the appender? – Quetzalcoatl Nov 16 '12 at 12:27
  • Yes, I use a log4j.properties file alongside my application to set other settings. But I don't know how I could dynamically adjust the "global" fileappender logfile. – Malvin Nov 16 '12 at 12:31

2 Answers2

1

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
vels4j
  • 11,208
  • 5
  • 38
  • 63
1

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)
dan
  • 13,132
  • 3
  • 38
  • 49
  • Thanks a lot! I initially thought that assigning the RootLogger to a "new" Logger would be "exclusive" for the specified Logger, but in fact it is "global", which is exactly what is required. – Malvin Nov 16 '12 at 12:52