I have a multithreaded application that executes several tasks in
parallel. Each task involves telnet and FTP connections and each task
is executed using a new thread. The overall application is controlled
using RMI.
The application must be able to retrieve the log entries for a given
task. This means retrieving the log entries for a given thread.
Furthermore this has to be performed synchronously by polling at
regular intervals to return the newest log entries.
I'm considering using the Log4j library by extending an appender and
using a pattern layout for formatting. What I need is a sort of a
memory appender which saves the log entries for each thread in a
buffer. It would then need to return the newest entries upon each
call.
A few questions:
1) Are there better alternatives to log4J?
2) Should I use one Log4j instance with multiple memory appenders for
each thread? This means I need to manage these with a list of
appenders.
3) Is there a better way by using multiple instances of Log4j, i.e. one
for each thread?
Thanks.
Domagoj Klepac - 25 May 2006 15:31 GMT
>A few questions:
>1) Are there better alternatives to log4J?
No.
>2) Should I use one Log4j instance with multiple memory appenders for
>each thread? This means I need to manage these with a list of
>appenders.
>3) Is there a better way by using multiple instances of Log4j, i.e. one
>for each thread?
You don't instantiate Log4j, you just instantiate logger for every
class which logs something:
public class MyClass {
private static Logger log = Logger.getLogger(MyClass.class);
public static void main(String[] args) {
log.info("Log something...");
}
}
There are several ways to separate log entries for each thread. If
your threads don't use the same classes, you could use:
public class MyClass {
private static Logger log = Logger.getLogger("Thread1");
public void myMethod() {
log.info("Log something for Thread1");
}
}
public class MyOtherClass {
private static Logger log = Logger.getLogger("Thread2");
public void myMethod() {
log.info("Log something for Thread2");
}
}
...and thus have separate loggers for each thread.
Or you might want to use NDC/MDC - check log4j docs for that one.
Domchi

Signature
Ouroboros ltd. - http://www.ouroboros.hr
Antispam: to reply, remove extra monkey from reply-to address.
dimitar - 25 May 2006 15:53 GMT
CharArrayWriter sink = new CharArrayWriter();
Layout layout = ....;
Logger logger = Logger.getLogger("ftp-session." + sessionId);
logger.setAppender(new WriterAppender(layout, sink))
Oliver Wong - 25 May 2006 16:25 GMT
> 3) Is there a better way by using multiple instances of Log4j, i.e. one
> for each thread?
You may want to look at the ThreadLocal class:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ThreadLocal.html
- Oliver