我希望能够在logback中动态更改单个appender的过滤级别
例如,如果我有
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d [%X{traceId}] [%thread] %-5level %logger{36} %marker - %msg%n</pattern>
</encoder>
</appender>
<!-- Root Config -->
<root level="${log_level:-INFO}">
<appender-ref ref="ASYNC-SERVICE"/>
<appender-ref ref="STDOUT"/>
</root>
我如何在运行时更改STDOUT appender以允许调试vs信息?
我可以轻松地全局更改根级别:
def setLogLevel(value: Level, loggerName: String = org.slf4j.Logger.ROOT_LOGGER_NAME) = {
val logger = LoggerFactory.getLogger(loggerName).asInstanceOf[Logger]
logger.setLevel(LogbackLevel.valueOf(value.toString))
}
但是我真的想控制哪个appender动态地获得哪个级别。
我尝试在appender上操作级别过滤器,但这似乎没有做太多
答案 0 :(得分:1)
我最终做的是让根级别始终记录在Debug并为每个appender提供阈值过滤器:
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level>
</filter>
<encoder>
<pattern>%d [%X{traceId}] [%thread] %-5level %logger{36} %marker - %msg%n</pattern>
</encoder>
</appender>
<!-- Root Config -->
<root level="${log_level:-DEBUG}">
<appender-ref ref="ASYNC-SERVICE"/>
<appender-ref ref="STDOUT"/>
</root>
然后我使用了groovy logback api中的ConfigurationDelegate类来查询appenders
val context = LoggerFactory.getILoggerFactory.asInstanceOf[LoggerContext]
val configuration = {
val delegate = new ConfigurationDelegate
delegate.setContext(context)
delegate
}
/**
* Sets the log level for a particular appender
* @param value
* @param appenderName
*/
def setAppenderLevel(value: Level, appenderName: String) = {
appenders.find(_.getName == appenderName) match {
case Some(appender) =>
val filters = appender.getCopyOfAttachedFiltersList
filters.find(_.isInstanceOf[ThresholdFilter]).foreach(m => m.asInstanceOf[ThresholdFilter].setLevel(value.toString))
case None =>
}
}
我查找了阈值过滤器并手动设置了值。