I have a java application which has 'hypothetically speaking' 3 objects... 1 of the class Animal, 1 of the class Food, those are not related by any inheritance or interface. and a last one of the class Manager which has a list of animals and list of Food, the manager is responsible for a zoo where those animals and Food are.
I am using log4j and I need to log to the a txt file IF ONLY AND ONLY IF something in the animal list changes... (animal dies, is born or what ever...) and I need to log to the System.out IF AND ONLY IF something in the Food list changes... (new food is need, food was eaten, what ever...)
How can I do that with log4j?
I have found here: Log4j : Creating/Modifying appenders at runtime, log file recreated and not appended
something like dynamically changing the appender
String targetLog="where ever you want your log"
FileAppender apndr = new FileAppender(new PatternLayout("%d %-5p [%c{1}] %m%n"),targetLog,true);
logger.addAppender(apndr);
logger.setLevel((Level) Level.ALL);
but I think this is very ugly and error prone to add and remove the appender constantly all over the hole application..
Is there any better way to handle this can I have 2 logger (one for animals 1 for the food)?
any suggestion?
Thanks
This is how I got it to work:
log4j.rootLogger=TRACE, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%5F:%t:%L] - %m%n
log4j.appender.animalLogger=org.apache.log4j.FileAppender
log4j.appender.animalLogger.File=animal.log
log4j.appender.animalLogger.layout=org.apache.log4j.PatternLayout
log4j.appender.animalLogger.layout.ConversionPattern=%d [%5F:%t:%L] - %m%n
log4j.category.animalLogger=DEBUG, animalLogger
log4j.additivity.animalLogger=false
log4j.category.foodlLogger=DEBUG, stdout
log4j.additivity.foodlLogger=false
static final Logger animalLogger = Logger.getLogger("animalLogger");
static final Logger foodlLogger = Logger.getLogger("foodlLogger");
and to load the logger and logging:
public static void main(String[] args) {
PropertyConfigurator.configure("log4j.properties");
animalLogger.debug("Hello animalLogger message");
foodlLogger.debug("Hello reportsLog message");
}