I want to write log for each thread using log4j and log file name will be \"workthread..log\",first thread print log on file \"workthread-1.log\" and second thread on \"work
Implement a new log appender which manages FileAppender for different thread and files. Use AppenderSkeleton to do this, maintain a map for FileAppenders.
public MultiThreadAppender extends AppenderSkeleton {
public final static String THREAD_KEY = "THREAD_NO";
private Map fileAppenders;
}
Use MDC to identify different threads. Use a key like "THREAD_NO", put to MDC (MDC.put) when a thread invoke logger the first time, and check this key to get the FileAppender for it. Here's the example:
protected void append(LoggingEvent event) {
Object value = event.getMDC(THREAD_KEY);
FileAppender appender;
if (value instanceof String && ((String) value).length() > 0) {
appender = fileAppenders.get(value);
} else {
value = nextThreadNo();
fileAppenders.put(value, new FileAppender(...)); //
}
}