how to temporarily make a field thread local

2019-09-16 12:36发布

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?

1条回答
对你真心纯属浪费
2楼-- · 2019-09-16 13:09

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.

查看更多
登录 后发表回答