I am trying to create multiple static loggers using Threadlocal, so that each static threadlocal will then log to seperate files with different messages. Below is my sample code:
public class LoggerTest implements Runnable
{
private static ThreadLocal<Logger> log=new ThreadLocal<Logger>();
FileHandler fh;
String str;
public LoggerTest(int counter,String instanceName) throws SecurityException, IOException
{
str=instanceName;
log.set(Logger.getLogger("Logging"+counter));
log.get().info("m");
fh=new FileHandler(instanceName+".log");
fh.setFormatter(new SimpleFormatter());
log.get().addHandler(fh);
}
public static void main(String[] args) throws SecurityException, IOException
{
Thread t1=new Thread(new LoggerTest(1, "file"+1),"Thread1");
Thread t2=new Thread(new LoggerTest(2, "file"+2),"Thread2");
Thread t3=new Thread(new LoggerTest(3, "file"+3),"Thread3");
t1.start();t2.start();t3.start();
}
@Override
public void run()
{
for (int i = 0; i < 10; i++)
{
log.get().info("Message"+i);
try
{
Thread.sleep(5000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
According to this every thread will have its own static ThreadLocal variables. So i've created 3 threads to log in different files by using ThreadLocal. Can someone point where am i going wrong in understanding the concept of static ThreadLocal's
My objective: To achieve multiple loggers using static ThreadLocal's TIA!!!