Jen*_*der 9 java testing logging logback slf4j
我正在尝试调整一些logback功能(自定义Appender等).为了测试它,我想配置Logback并直接调用它的日志记录方法而不通过sl4j.
这种奇怪要求的原因是能够在其他SLF4J桥接可用的环境中测试回溯功能.
所以我想做这里描述的内容:http://logback.qos.ch/manual/configuration.html#joranDirectly,没有引用SLF4J
小智 5
有一种方法可以找出答案。
以下是如何配置 LOGBack 的示例
// Here we create context
LoggerContext loggerContext = new LoggerContext();
// Initializer is used to enrich context with details
ContextInitializer contextInitializer = new ContextInitializer(loggerContext);
try {
// Get a configuration file from classpath
URL configurationUrl = Thread.currentThread().getContextClassLoader().getResource("custom-logback-configuration.xml");
if (configurationUrl == null) {
throw new IllegalStateException("Unable to find custom logback configuration file");
}
// Ask context initializer to load configuration into context
contextInitializer.configureByResource(configurationUrl);
// Here we get logger from context
logger = loggerContext.getLogger(LogReporter.class);
} catch (JoranException e) {
throw new RuntimeException("Unable to configure logger", e);
}
Run Code Online (Sandbox Code Playgroud)
一般来说,如果您想了解 SLF4J 后端是如何工作的,您可以只查看该后端的 org.slf4j.impl.StaticLoggerBinder 类源代码。
还没有尝试过,但看起来是正确的,也许会有所帮助:
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
ch.qos.logback.classic.Logger log = lc.getLogger(foo.Bar.class);
Run Code Online (Sandbox Code Playgroud)
工具但是你可以直接使用它ch.qos.logback.classic.Logger。org.slf4j.Logger您可能需要以LoggerContext不同的方式获取。
| 归档时间: |
|
| 查看次数: |
2862 次 |
| 最近记录: |