Logging into different files based on some condition

前端 未结 1 1046
鱼传尺愫
鱼传尺愫 2021-01-27 06:46

We have an application. In which we have a condition.Based on the condition, if it is true then we will write some log messages to one file else we will log the messages to anot

相关标签:
1条回答
  • 2021-01-27 07:00

    This is supported out of the box. Here is my example:

    server:
      rootPath: /api/*
      requestLog:
        appenders: []
      applicationConnectors:
      - type: http
        port: 9085
    logging:
      level: INFO
      loggers:
        "my-log-1":
          level: DEBUG
          additive: false
          appenders:
            - type: file
              currentLogFilename: /home/artur/var/log/test1.log
              archivedLogFilenamePattern: /home/artur/var/log/test1.log%d.log.gz
              archivedFileCount: 5
              logFormat: '[%level] %msg%n'
        "my-log-2":
          level: DEBUG
          additive: false
          appenders:
            - type: file
              currentLogFilename: /home/artur/var/log/test2.log
              archivedLogFilenamePattern: /home/artur/var/log/test2.log%d.log.gz
              archivedFileCount: 5
    

    NOTE: You can not use tabs in the configuration.

    This configuration creates 2 loggers. First is called "my-log-1", second is called "my-log-2".

    You can now create these loggers in your java class, for example in my application:

    public class Application extends io.dropwizard.Application<Configuration>{
    
    
        private static final Logger log = Logger.getLogger("my-log-1");
        private static final Logger log2 = Logger.getLogger("my-log-2");
    
    
        @Override
        public void run(Configuration configuration, Environment environment) throws Exception {
    
            log.info("Test1"); // writes to first file
            log2.info("Test2"); // logs to seconds file
    
    
    
        }
    
        public static void main(String[] args) throws Exception {
            new Application().run("server", "/home/artur/dev/repo/sandbox/src/main/resources/config/test.yaml");
        }
    }
    

    Note the two loggers and their creation at the top of the file.

    You can now use them like any logger. Add your condition and log away:

            int random = new Random().nextInt();
    
            if(random % 2 == 0) {
                log.info("Test1"); // writes to first file
            } else {
                log2.info("Test2"); // logs to seconds file
            }
    

    I hope that answers your question,

    thanks,

    Artur

    0 讨论(0)
提交回复
热议问题