Logback日志框架如何限制日志最长打印长度?

在程序中,我们一般不希望在运行时打印过长的日志,所以我们需要对日志进行长度限制。以下就是对日志进行长度限制的步骤。

1. 编写过滤器

在程序中新建CustomLengthFilter过滤器类,内容如下:

public class CustomLengthFilter extends Filter<ILoggingEvent> {
private int maxLength;
@Override
public FilterReply decide(ILoggingEvent event) {
String message = event.getMessage();
if (message != null && message.length() > maxLength) {
// 消息长度超过指定的最大长度,拒绝打印
return FilterReply.DENY;
}
return FilterReply.NEUTRAL;
}
public void setMaxLength(int maxLength) {
this.maxLength = maxLength;
}
}

2. 编写Logback.xml

resources目录下新建Logback.xml

<configuration>
<!-- 引入SpringBoot默认的logback配置文件 -->
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<!-- 其他配置 -->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
</encoder>
<!-- 添加自定义过滤器(这里填写你自己的包路径) -->
<filter class="com.filter.CustomLengthFilter">
<maxLength>500</maxLength>
</filter>
</appender>
<root level="INFO">
<appender-ref ref="CONSOLE" />
</root>
</configuration>

本文作者:护发师兄

本文链接:https://www.cnblogs.com/jonil/p/17696445.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   护发师兄  阅读(1065)  评论(2编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起