0

I'd like to output logging for a specific amount of time and for a selection of classes to a second file. Right now I use this code:

FileAppender appender = new FileAppender(new PatternLayout(PATTERN), filePath);                 
Logger.getRootLogger().addAppender(appender);
log.info("test");
appender.close();

This does work for logging for a limited time, but instead of specific classes, all my logging is output to the second logfile. An alternative is using class specific logging:

FileAppender appender = new FileAppender(new PatternLayout(PATTERN), filePath);                 
Logger.getLogger(A.class).addAppender(appender);
Logger.getLogger(B.class).addAppender(appender);
Logger.getLogger(C.class).addAppender(appender);
log.info("test");
appender.close();

Which is closer to what I want, but it's hard to make an exhaustive list of the classes in use.

Is it possible to programmatically add an appender based on thread or based on package name?

Cloud
  • 458
  • 1
  • 13
  • 34
  • I really think you should study the [log4j manual](https://logging.apache.org/log4j/1.2/manual.html) because it seems like you're not taking advantage of log4j as well as you could be. The loggers are hierarchical so if you obtain your logger by calling getLogger(My.class) in each of your classes it's very easy to modify your configuration file to send messages from a specific package to special appenders. Also, by using a config file you avoid using code that is not part of the intended public API so migration to newer versions of log4j will be easier in the long run. – D.B. Dec 10 '16 at 07:58
  • I considered using text configuration, but I can't find info on how to temporarily enable such an appender and being able to specify the output file of the appender in my code. If that is possible, I'd prefer the text configuration. – Cloud Dec 10 '16 at 11:58
  • What exactly do you mean when you say temporarily enable? – D.B. Dec 10 '16 at 15:36
  • I'd like to capture the log output of a single import action of an admin on my web application. So the user triggers the imports, this starts the logging, the action (afterwards ending the logging) and the user can download the logfile with only the details of this import. With additivity enabled, the global log will still log fine. – Cloud Dec 10 '16 at 17:46
  • Perhaps [this](http://stackoverflow.com/a/3870364/3284624) answer would be useful to you for your purposes. I would suggest using a named logger for this, perhaps name it "importActionLog" or something similar then in your code you can call Logger.getLogger("importActionLog") and use the logger from this call to generate the log you want. – D.B. Dec 10 '16 at 18:34

0 Answers0