Logging into different files based on some condition

偶尔善良 提交于 2019-12-02 09:49:58

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

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