我已使用LogbackValve为Tomcat 7.0启用了logback-access日志。 我的logback-access配置看起来像这样。
<configuration>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>access.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>access.%d{yyyy-MM-dd}.log.zip</fileNamePattern>
</rollingPolicy>
<encoder>
<pattern>combined</pattern>
</encoder>
</appender>
<appender-ref ref="FILE" />
</configuration>
现在这很完美,我可以看到访问日志。但在其他一些代码中,我想以编程方式检索在logback-access.xml中配置的appender。有没有办法做到这一点。由于没有定义Logger,因此无法使用LoggerContext。
答案 0 :(得分:0)
您可以使用LogbackAccessContext来检索在logback-access.xml中配置的附加程序。这是我的解决方案:
TomcatServletWebServerFactory sc = (TomcatServletWebServerFactory) context.getBean(TomcatServletWebServerFactory.class);
List<Valve> values = (List<Valve>) sc.getEngineValves();
LogbackAccessTomcatValve accessTomcatValve = null;
for(Valve value : values) {
if(value.getClass() == LogbackAccessTomcatValve.class) {
accessTomcatValve = (LogbackAccessTomcatValve) value;
}
}
//get logbackAccessContext from the logbackAccessTomcatValve by invoking.
LogbackAccessContext logbackAccessContext = null;
Field field = null;
try {
field = accessTomcatValve.getClass().getDeclaredField("logbackAccessContext");
field.setAccessible(true);
logbackAccessContext = (LogbackAccessContext) field.get(accessTomcatValve);
} catch (Exception e) {
log.error("Exception happened when fetching the logback access context ." +e.getMessage());
}