log4j, threading and appenders

S

simonboland

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.
 
D

Domagoj Klepac

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
 
D

dimitar

CharArrayWriter sink = new CharArrayWriter();
Layout layout = ....;
Logger logger = Logger.getLogger("ftp-session." + sessionId);
logger.setAppender(new WriterAppender(layout, sink))
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top