How to log multiple threads in different log files?

前端 未结 6 659
南旧
南旧 2020-12-05 12:40

I have a JAVA class that starts various threads that have unique IDs. Each thread should log into a unique log file, named after the ID.log.

Because I only get the u

6条回答
  •  自闭症患者
    2020-12-05 13:06

    As far as I can tell ThreadLocal API was designed to do what you describe.

    Code like below would establish per-thread loggers each using own (per-thread) FileAppender:

    /**
     * usage: threadLocalLogger.get().info("hello thread local logger")
     */
    static ThreadLocal threadLocalLogger = newThreadLocalLogger("myJobId");
    
    private static ThreadLocal newThreadLocalLogger(final String myJobID) {
        return new ThreadLocal() {
            @Override
            protected Logger initialValue() {
                return logger(myJobID, Thread.currentThread().getId());
            }
        };
    }
    
    private static Logger logger(String myJobID, long threadId) {
        // Initialize the logger
        String loggerId = myJobID + "-" + threadId;
        Logger myLogger = Logger.getLogger(loggerId);
        FileAppender myFileAppender;
        try
        {
            myFileAppender = new FileAppender(new SimpleLayout(),
                    loggerId + ".log", false);
            BasicConfigurator.resetConfiguration();
            BasicConfigurator.configure(myFileAppender);
        } catch (IOException e1) {
        // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return myLogger;
    }
    

提交回复
热议问题