Java Logback:如何仅将错误记录到文件中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19689223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Logback: how to log only errors to file
提问by Mister Smith
I've been reading the logback manual for 2 hours and still can't figure how to do what I need.
我已经阅读了 2 个小时的 logback 手册,但仍然无法弄清楚如何做我需要的。
It is as simple as the title says: I want to log only the errors to a file, and the other levels (including ERROR) to console.
正如标题所说的那样简单:我只想将错误记录到文件中,而将其他级别(包括错误)记录到控制台。
This is the root section of my logcat.xml file:
这是我的 logcat.xml 文件的根部分:
<root level="TRACE" >
<appender-ref ref="CONSOLE_APPENDER" />
<appender-ref ref="FILE_APPENDER" />
</root>
The problem with this configuration is that it logs every level >= TRACE to both appenders.
此配置的问题在于它将每个级别 >= TRACE 记录到两个 appender。
I could let the root with only console, and define a file logger:
我可以让 root 只有控制台,并定义一个文件记录器:
<logger name='file_logger' level='ERROR' >
<appender-ref ref="FILE_APPENDER" />
</logger>
But then I'd have to call the normal logger like this:
但是我必须像这样调用普通的记录器:
LoggerFactory.getLogger(ClientClass.class);
And the file logger like this:
文件记录器是这样的:
LoggerFactory.getLogger("file_logger");
I don't wan't to choose the logger for each class. I just want to get the root logger from the factory using the class as parameter, and have it do the correct thing depending on the level.
我不想为每个班级选择记录器。我只想使用类作为参数从工厂获取根记录器,并让它根据级别做正确的事情。
Is this possible?
这可能吗?
采纳答案by steffen
Put this into your file appender definition:
把它放到你的文件附加器定义中:
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
The ThresholdFilter
is in logback-classic.jar
.
该ThresholdFilter
是logback-classic.jar
。
回答by Anton Pryamostanov
I don't understand why wrong answer here is upvoted. The guy wants ONLY error messages in his file.
我不明白为什么这里的错误答案被赞成。这家伙只想要他的文件中的错误消息。
Here is the correct answer:
以下是正确答案:
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
Reference: https://logback.qos.ch/manual/filters.html#levelFilter
回答by Hardik Rana
Refer below code:
参考以下代码:
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>DENY</onMatch>
<onMismatch>ACCEPT</onMismatch>
</filter>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>