-3

I have a java application which has 'hypotetically 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 wich is having a list of animals and list of Food, the manager is responsable for a zoo where those animals and Food are..

to the point...

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, borns 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...)

My question:

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

Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97

2 Answers2

0

You can do this strictly from the configuration in the log4j.xml file. You can define two appenders in there, and then have two logger elements, one that ties animals to the first appender, and one that ties the food to another appender. Probably you should have a element too, to define default behavior.

John Kelty
  • 107
  • 8
0

This is how I got it to work:

Configuring the properties

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");
} 
Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97