简体   繁体   中英

Java/Logging: How to log to separate log file every time?

I am writing a command line Java program where every-time the app is started, I want to log to a new file(for now, I am using the current timestamp as the log file's name). My app also makes use of number of libraries that also log stuff. How do dynamically create a logger which will take both my code's logging + any logs done by libraries and redirect it to both the console + a new file? I am using SLF4j + logback. So far, I have something like below which can create logger dynamically but this logger doesn't capture third-party loggings:

public static Logger createLogger(String pattern) {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

        PatternLayoutEncoder layoutEncoder = new PatternLayoutEncoder();
        layoutEncoder.setPattern(pattern);
        layoutEncoder.setContext(loggerContext);
        layoutEncoder.start();

        FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
        fileAppender.setFile(System.currentTimeMillis() + ".log");
        fileAppender.setEncoder(layoutEncoder);
        fileAppender.setContext(loggerContext);
        fileAppender.start();


        ch.qos.logback.classic.Logger logger = loggerContext.getLogger("customLogger");
        logger.addAppender(fileAppender);
        logger.setLevel(Level.TRACE);
        logger.setAdditive(true);

        return logger;
    }

It's possible to do this entirely through configuration. There's an example in the logback documentation :

<configuration>

  <!-- Insert the current time formatted as "yyyyMMdd'T'HHmmss" under
       the key "bySecond" into the logger context. This value will be
       available to all subsequent configuration elements. -->
  <timestamp key="bySecond" datePattern="yyyyMMdd'T'HHmmss"/>

  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <!-- use the previously created timestamp to create a uniquely
         named log file -->
    <file>log-${bySecond}.txt</file>
    <encoder>
      <pattern>%logger{35} - %msg%n</pattern>
    </encoder>
  </appender>

  <root level="DEBUG">
    <appender-ref ref="FILE" />
  </root>
</configuration>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM