slf4j+logback使用LoggingEventCompositeJsonEncoder输出json乱码
公司的微服务接入ELK后,输出的日志,其中中文是unicode编码,进行问题定位的时候,中文参数无法看出是什么。并且原先的日志中,配置的timeZone是格林威治时区GMT,看日志的输出时间也不方便,所以修改下日志的配置。
解决方案: 1.修改引入的jar包版本
<dependency> <groupId>net.logstash.logback</groupId> <artifactId>logstash-logback-encoder</artifactId> <version>5.2</version> </dependency>
2.logback-spring.xml中增加配置解决中文乱码
<jsonFactoryDecorator class="net.logstash.logback.decorate.CharacterEscapesJsonFactoryDecorator"> <escape> <targetCharacterCode>10</targetCharacterCode> <escapeSequence>u2028</escapeSequence> </escape> </jsonFactoryDecorator>
完整的日志节点如下:
<!-- 使用json格式保存日志文件 --> <appender name="JSON_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${LOG_HOME}/${springAppName}-common.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <!-- 活动文件的名字会根据fileNamePattern的值,每隔一段时间改变一次 --> <fileNamePattern>${LOG_HOME}/${springAppName}-common.%d.%i.log</fileNamePattern> <!-- 每产生一个日志文件,该日志文件的保存期限为10天 --> <maxFileSize>200MB</maxFileSize> <maxHistory>10</maxHistory> <totalSizeCap>2GB</totalSizeCap> </rollingPolicy> <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder"> <!--如下是新增的配置,解决中文乱码--> <jsonFactoryDecorator class="net.logstash.logback.decorate.CharacterEscapesJsonFactoryDecorator"> <escape> <targetCharacterCode>10</targetCharacterCode> <escapeSequence>u2028</escapeSequence> </escape> </jsonFactoryDecorator> <providers> <pattern> <pattern> { "timestamp": "%date{"yyyy-MM-ddTHH:mm:ss,SSSZ"}", "severity": "%level", "service": "${springAppName:-}", "env": "${springProfile:-}", "trace": "%X{X-B3-TraceId:-}", "TxId": "%X{PtxId}", "span": "%X{X-B3-SpanId:-}", "parent": "%X{X-B3-ParentSpanId:-}", "exportable": "%X{X-Span-Export:-}", "pid": "${PID:-}", "thread": "%thread", "class": "%logger{40}", "rest": "%message", "exception": "%exception{full}" } </pattern> </pattern> </providers> </encoder> </appender>