Just some ideas... 1) In the main() method, create a single ConsoleAppender and attach it to the root logger.
2) In the threads, have some synchronized code to ensure that only one ConsoleAppender is created and attached. 3) Chuck the entire idea of configuring/synchronizing all the log4j components (like appenders) directly in code and use a configuration file that sets everything up (or at least only creates one ConsoleAppender per logger). I don't know if any of those match what you really want to do. -Mark > -----Original Message----- > From: Alan Simpson [mailto:[EMAIL PROTECTED]] > Sent: Wednesday, July 03, 2002 9:05 AM > To: [EMAIL PROTECTED] > Subject: threading problems with log4j > > > > hi, > > I ran the following code. In it, I make three threads and in > each of them, I > get a Logger object, add a ConsoleAppender and then log three > items. The > idea, as you can no doubt tell, is to mimick using a class > with logging in > it within a multithread environment. > > I would have hoped to have gotten nine logging messages > (three logging calls > within each of three threads). Instead, I typically get 21 > messages with > some duplicates. > > The reason, of course, is that the logger.info() calls are > appending to all > of the appenders attached at that time to the logger in all > of the threads. > > Any ideas for a work-around? > > thanks! > > =========== > > import org.apache.log4j.ConsoleAppender; > import org.apache.log4j.Logger; > import org.apache.log4j.PatternLayout; > > public class MultiThreadTest > { > public static void main(String[] args) > { > for (int i=0; i<3; i++) > { > TestThread tt = new TestThread(i); > tt.start(); > } > } > } > > class TestThread extends Thread > { > private int threadID; > > TestThread(int id) > { > threadID = id; > } > > public void run() > { > Logger logger = Logger.getLogger("MultiThreadTest"); > ConsoleAppender cAppender = new > ConsoleAppender(new PatternLayout()); > logger.addAppender(cAppender); > > for (int i=0; i<3; i++) > { > logger.info("item"+threadID+":"+i); > } > } > } > > > _________________________________________________________________ > MSN Photos is the easiest way to share and print your photos: > http://photos.msn.com/support/worldwide.aspx > > > -- > To unsubscribe, e-mail: > <mailto:[EMAIL PROTECTED]> > For additional commands, e-mail: > <mailto:[EMAIL PROTECTED]> > -- To unsubscribe, e-mail: <mailto:[EMAIL PROTECTED]> For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>
