0

Dears,

Currently i'm running an web application which uses log4j for logging purposes. My application use Multi-threading concept and my log4j works fine if threads are started in sequential.

If i start multitasking then 1st thread log are logged into 2nd task thread and vice-versa. Hence the logs are mixed up.

While calling another methods of every class i'm just passing my appender as an arguments. And i am calling the appender as below in every class as required

private FileAppender appender = new FileAppender();
log.addAppender(appender);

How can i differentiate the appender log files based on task that are started in parallel.

Thanks

Karthick88it
  • 601
  • 2
  • 12
  • 28
  • you should show some code, to understand – Eugene Mar 15 '17 at 06:04
  • In each and every class i'm calling ` Logger log = Logger.getLogger(classname.class); FileAppender appender = new FileAppender();` So the instance is static and the logs are getting mixed up – Karthick88it Mar 15 '17 at 06:48
  • AFAIK, appenders are better to configure in `log4j.properties` file. This way you may end up with many orphaned appenders for one logger (if not to call `removeAppender`). Anyway, I would suggest to synchronize adding appender to logger: `synchronized(log){ log.addAppender(appender); }` – Eugene Mar 15 '17 at 09:42

1 Answers1

0

As I understood, you need to match the logged string with the thread origin. You can use Nested Diagnostic Context (see http://www.baeldung.com/java-logging-ndc-log4j, and https://stackoverflow.com/a/22150615/7670475 .

Community
  • 1
  • 1
S. Stas
  • 800
  • 4
  • 8