CosminO
CosminO

Reputation: 5226

log4j- using specific logger but showing the class name

Until now, I've used a method with log4j like this:

void writeMethod(String msg){
  StackTraceElement[] st = Thread.currentThread().getStackTrace();
  Logger log=Logger.getLogger(st[2]);
  log.info(msg);
}

This, together with the properties, allowed me to show in the log file the class/method which called the write method and it worked fine, for as long as I only needed one log file per application run. Now I have more threads per application and I need more than 1 log file per application (number can be, virtually, unlimited). Since I wish to have more than 1 log files, I create the log4j.properties file at application start time automatically and then use a specific appender for each thread of the application.

So the appenders are named like l0, l1, l2 .... and each one writes to a different log file.

This means that I am now using something like:

void writeMethod(int threadNr ,String msg){

      Logger log=Logger.getLogger("l"+threadNr);
      log.info(msg);
    }

My question is: can I use this second method AND also have the previous functionality of being able to write the method/class which called the logging method?

Upvotes: 0

Views: 1181

Answers (1)

TedTrippin
TedTrippin

Reputation: 3657

I use a properties file to configure my log4j. Example of a layout...

log4j.appender.R.layout.ConversionPattern=%d %5p [%t] (%F:%L) - %m%n

And here's a link to a log4j reference. If you want files for each thread you could always create multiple appenders and create logger for each one. Eg.

// In your log4j config
log4j.logger.1=DEBUG

// In you code
Logger log = Logger.getLogger("1.ClassName");

Upvotes: 1

Related Questions