how to temporarily make a field thread local

天涯浪子 提交于 2020-01-06 16:33:56

问题


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:


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.



来源:https://stackoverflow.com/questions/23748583/how-to-temporarily-make-a-field-thread-local

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!