本文介绍了使用Java而非XML在Spring下配置Logback的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Spring [Boot]下,如何使用JavaConfig或某种基于注释的配置以编程方式配置Logback. 我希望尽可能避免使用XML文件

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

欢迎示例

我不在寻找指向以下内容的链接.我已经有这些了.假设我有这些,我的问题是如何达到这个问题的目标.How to configure Lockback in Java when NOT under SpringHow to set up Logback under Spring or Spring Boot using XML

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 SpringHow to set up Logback under Spring or Spring Boot using XML

推荐答案

是.如果要以编程方式进行配置,则是可能的.例如,下面的代码对我有用:

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;
  }
}

这篇关于使用Java而非XML在Spring下配置Logback的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 00:45