gpt4 book ai didi

java - Logback 具有不同配置的多个记录器

转载 作者:行者123 更新时间:2023-11-30 10:33:39 24 4
gpt4 key购买 nike

我想在一个类中使用 2 个不同的记录器,其中一个记录器使用一个 logback 配置文件,另一个使用另一个配置文件。例如:

class Sample {
// LOGGER 1 follows configuration from logback1.xml
private static final LOGGER1 = LoggerFactory.getLogger(Sample.class);

// LOGGER 2 follows configuration from logback2.xml
private static final LOGGER2 = LoggerFactory.getLogger(Sample.class);

public myFunc(){
LOGGER1.info("In myFunc"); // writes to file as configured in logback1.xml
LOGGER2.info("Entered myFunc"); // writes to graylog server as configured in logback2.xml
}
}

我想这样做的原因是我在运行时将第二个记录器注入(inject)到代码中,我不希望注入(inject)的记录器与主项目中使用的记录器发生冲突。我应该怎么做?

我浏览了这篇文章:How to use multiple configurations with logback in a single project?但它似乎解决了从许多配置文件中选择一个而不是“能够像上面的例子那样同时使用 2 个配置文件”的问题。

最佳答案

这是从不同配置获取两个记录器的一种方法:

    LoggerContext c1 = new LoggerContext();
LoggerContext c2 = new LoggerContext();
new ContextInitializer(c1).configureByResource(new URL("file:logback1.xml"));
new ContextInitializer(c2).configureByResource(new URL("file:logback2.xml"));
Logger l1 = c1.getLogger("x");
Logger l2 = c2.getLogger("x");

关于java - Logback 具有不同配置的多个记录器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42105302/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com