Logging parallel threads in logback

前端 未结 4 586
生来不讨喜
生来不讨喜 2021-02-06 03:10

I\'ll try to make a brief description of my Selenium framework so that I can explain my problem.

I use Selenium 2 (current version 2.3.1) + test

4条回答
  •  南方客
    南方客 (楼主)
    2021-02-06 03:36

    If you would like an alternative to the unpredictable names you get with %thread as I usually do, you can use simple thread-local IDs. Its much easier on the eyes. This will work with logback...

    public class ThreadIdConverter extends ClassicConverter {
      private static int nextId = 0;
      private static final ThreadLocal threadId = new ThreadLocal() {    
        @Override
        protected String initialValue() {
          int nextId = nextId();
          return String.format("%05d", nextId);
        }
      };
    
      private static synchronized int nextId() {
        return ++nextId;
      }
    
      @Override
      public String convert(ILoggingEvent event) {
        return threadId.get();
      }
    }
    

    Then put this simple line in your logback XML:

    
    

    Set your pattern something like this (notice "tid"):

    %d{HH:mm:ss.SSS} [%tid] %-5level - %msg%n
    

    And your logs will look like this:

    10:32:02.517 [00001] INFO something here
    10:32:02.517 [00002] INFO something here
    10:32:02.517 [00003] INFO something here
    10:32:02.517 [00001] INFO something more here 
    10:32:02.517 [00001] INFO something more here
    

    You can do this with any logger that supports custom extensions. Hope it helps.

提交回复
热议问题