Configure Logback under Spring using Java and Not XML

独自空忆成欢 提交于 2019-12-13 03:34:23

问题


Under Spring[Boot], how do you configure Logback programmatically either using JavaConfig or some kind of Annotation-based configuration. I wish to avoid XML files as much as possible

Examples are welcome

I am NOT looking for links to the following. I already have these. Assuming I have these, my question is how to get to the goal of this question. How to configure Lockback in Java when NOT under Spring How to set up Logback under Spring or Spring Boot using XML


回答1:


Yes. It's possible if you want to configure programmatically. For example, below code is work for me:

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.FileAppender;
import org.slf4j.LoggerFactory;

public class LoggerUtil {
  public static void main(String[] args) {
    Logger example1 = createLoggerFor("example1", "example1.log");
    Logger example2 = createLoggerFor("example2", "example2.log");
    example1.info("test-example1");
    example2.info("test-example2");
  }

  private static Logger createLoggerFor(String string, String file) {
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder();

    patternLayoutEncoder.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
    patternLayoutEncoder.setContext(loggerContext);
    patternLayoutEncoder.start();
    FileAppender<ILoggingEvent> fileAppender = new FileAppender<ILoggingEvent>();
    fileAppender.setFile(file);
    fileAppender.setEncoder(patternLayoutEncoder);
    fileAppender.setContext(loggerContext);
    fileAppender.start();

    Logger logger = (Logger) LoggerFactory.getLogger(string);
    logger.addAppender(fileAppender);
    logger.setLevel(Level.DEBUG);
    logger.setAdditive(false); /* set to true if root should log too */

    return logger;
  }
}


来源:https://stackoverflow.com/questions/57014740/configure-logback-under-spring-using-java-and-not-xml

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