Reputation: 159
My class is like this, basically I'm writing a servlet, and I want to change the log level for a specific user connected to my servlet and leave other log settings for other user unchanged, since the server will produce one thread to serve one client, I'm writing demo code use only threads
public Class A implements Runnable {
Logger myLogger = new Logger();
@Override
public void run() {
if (Thread.currentThread.getName()).equals("something") {
// some code that makes myLogger thread-local so I can change
// myLogger settings without affecting other threads
}
myLogger.debug("some debug information");
}
}
Any ideas how to do it?
Upvotes: 0
Views: 240
Reputation: 995
Seems like this could be done in this way
public Class A implements Runnable {
private static final ThreadLocal<Logger> logger = new ThreadLocal<Logger>(){
//return your desired logger
}
@Override
public void run() {
//check condition and change logger if required
//check if that particular servlet and user also
if (Thread.currentThread.getName().equals("something") && user.getId() ==XX) {
ConsoleAppender a = (ConsoleAppender) Logger.getRootLogger().getAppender("stdout");
a.setLayout(new PatternLayout("%d{HH:mm:ss} %-5.5p %t %m%n"));
}
}
}
for more information: When and how should I use a ThreadLocal variable?
java doc for Thread Local states that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable more.
Upvotes: 2