Logging into different files based on some conditi

2019-03-05 13:28发布

问题:

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 another file.

And logging should be happened based on the condition and not based on log level.

How it is possible in dropwizard using yaml file?

回答1:

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