Spring Boot 使用logback自定义编码器限制消息大小

ryevplcw  于 2023-03-29  发布在  Spring
关注(0)|答案(2)|浏览(231)

我试图限制日志消息的大小,我成功地做到了这一点与错误追溯(使用ShortenedThrowableConverter),但我没有设法找到一个解决方案,以消息本身。
我知道一种方法是使用<pattern/>,但由于我自己实现了编码器。
我尝试使用布局,但遇到了以下错误:

no applicable action for [layout], current ElementPath  is [[configuration][appender][encoder][layout]]

下面是我的一些代码:
logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="console-json" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="com.test.log.logback.JsonEncoder">
            <throwableConverter class="net.logstash.logback.stacktrace.ShortenedThrowableConverter">
                <maxLength>20</maxLength>
            </throwableConverter>
        </encoder>
    </appender>

    <root level="info">
        <appender-ref ref="console-json" />
    </root>

    <shutdownHook class="ch.qos.logback.core.hook.DelayingShutdownHook"/>

    <contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
        <resetJUL>true</resetJUL>
    </contextListener>
</configuration>

编码器:

package com.test.log.logback;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.logstash.logback.stacktrace.ShortenedThrowableConverter;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class JsonEncoder extends net.logstash.logback.encoder.LogstashEncoder {

    private String customFields;
    ShortenedThrowableConverter converter = new ShortenedThrowableConverter();
    public JsonEncoder() {
        converter.setMaxLength(10);
        setThrowableConverter(converter);
        setFieldNames(new FieldNames());
        setTimeZone("UTC");
        setFindAndRegisterJacksonModules(false);
    }   
    
}
u0njafvf

u0njafvf1#

要在使用net.logstash.logback.encoder.LogstashEncoder时限制JSON输出中的message字段,您需要:
1.禁用默认message字段输出
1.使用模式提供程序添加自定义message字段
例如:

<encoder class="net.logstash.logback.encoder.LogstashEncoder">
    <!-- Disable the default message field -->
    <fieldNames>
        <message>[ignore]</message>
    </fieldNames>
    <!-- Add a new message field that truncates the message to 20 characters -->
    <provider class="net.logstash.logback.composite.loggingevent.LoggingEventPatternJsonProvider">
        <pattern>{"message":"%0.-20message"}</pattern>
    </provider>
</encoder>

或者作为自定义编码器:

public class JsonEncoder extends LogstashEncoder {
    @Override
    public void start() {
        // Disable the default message field
        getFieldNames().setMessage("[ignore]");

        // Add a new message field that truncates the message to 20 characters
        LoggingEventPatternJsonProvider patternProvider = new LoggingEventPatternJsonProvider();
        patternProvider.setContext(getContext());
        patternProvider.setPattern("{\"message\":\"%0.-20message\"}");
        addProvider(patternProvider);
        super.start();
    }
}

或者,您可以使用net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder(它是LogstashEncoder的超类),并完全按照您喜欢的方式使用JSON提供程序构建JSON事件。
例如:

<encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
    <providers>
        <pattern>
            <pattern>
                {
                "timestamp": "%date{ISO8601}",
                "message":"%0.-20message"
                }
            </pattern>
        </pattern>
        <!--
            To add additional fields to the JSON output, either
            add the fields to the above pattern, or
            add additional JSON providers here.
         -->
    </providers>
</encoder>

或者作为自定义编码器:

public class JsonEncoder extends LoggingEventCompositeJsonEncoder {
    @Override
    public void start() {
        getProviders().addProvider(new LoggingEventFormattedTimestampJsonProvider());

        LoggingEventPatternJsonProvider patternProvider = new LoggingEventPatternJsonProvider();
        patternProvider.setContext(getContext());
        patternProvider.setPattern("{\"message\":\"%0.-20message\"}");
        getProviders().addProvider(patternProvider);

        /*
         * To add additional fields to the JSON output, either
         * add the fields to the above pattern, or
         * add additional JSON providers here.
         */
        super.start();
    }
}
7fyelxc5

7fyelxc52#

我的版本:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <property resource="application.yml" />
    <contextName>Operator Platform</contextName>
    <springProfile name="!local">
        <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
            <encoder class="net.logstash.logback.encoder.LogstashEncoder">
                <fieldNames>
                    <message>[ignore]</message>
                </fieldNames>
                <provider class="net.logstash.logback.composite.loggingevent.LoggingEventPatternJsonProvider">
                    <pattern>{"message":"%0.-10500message"}</pattern>
                </provider>
                <throwableConverter class="net.logstash.logback.stacktrace.ShortenedThrowableConverter">
                    <maxDepthPerThrowable>30</maxDepthPerThrowable>
                    <maxLength>4096</maxLength>
                    <shortenedClassNameLength>40</shortenedClassNameLength>
                    <!-- generated class names -->
                    <exclude>\$\$FastClassByCGLIB\$\$</exclude>
                    <exclude>\$\$EnhancerBySpringCGLIB\$\$</exclude>
                    <exclude>^sun\.reflect\..*\.invoke</exclude>
                    <!-- JDK internals -->
                    <exclude>^com\.sun\.</exclude>
                    <exclude>^sun\.net\.</exclude>
                    <!-- dynamic invocation -->
                    <exclude>^net\.sf\.cglib\.proxy\.MethodProxy\.invoke</exclude>
                    <exclude>^org\.springframework\.cglib\.</exclude>
                    <exclude>^org\.springframework\.transaction\.</exclude>
                    <exclude>^org\.springframework\.validation\.</exclude>
                    <exclude>^org\.springframework\.app\.</exclude>
                    <exclude>^org\.springframework\.aop\.</exclude>
                    <exclude>^org\.springframework\.beans\.</exclude>
                    <exclude>^java\.lang\.reflect\.Method\.invoke</exclude>
                    <rootCauseFirst>true</rootCauseFirst>
                    <inlineHash>true</inlineHash>
                </throwableConverter>
                <providers>
                    <contextName>
                        <fieldName>app</fieldName>
                    </contextName>
                    <timestamp>
                        <fieldName>ts</fieldName>
                        <timeZone>UTC</timeZone>
                    </timestamp>
                    <loggerName>
                        <fieldName>logger</fieldName>
                    </loggerName>
                    <logLevel>
                        <fieldName>level</fieldName>
                    </logLevel>
                    <callerData>
                        <classFieldName>class</classFieldName>
                        <methodFieldName>method</methodFieldName>
                        <lineFieldName>line</lineFieldName>
                        <fileFieldName>file</fileFieldName>
                    </callerData>
                    <threadName>
                        <fieldName>thread</fieldName>
                    </threadName>
                    <mdc>
                        <fieldName>requestId</fieldName>
                    </mdc>
                    <arguments>
                        <includeNonStructuredArguments>false</includeNonStructuredArguments>
                    </arguments>
                    <stackTrace>
                        <fieldName>stack</fieldName>
                    </stackTrace>
                </providers>
            </encoder>
        </appender>
        <root level="INFO">
            <appender-ref ref="CONSOLE" />
        </root>
    </springProfile>
    <springProfile name="local">
        <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
            <encoder>
                <pattern>
                    %d{HH:mm:ss.SSS} | %5p | %logger{25} | %m%n
                </pattern>
                <charset>utf8</charset>
            </encoder>
        </appender>

        <root level="DEBUG">
            <appender-ref ref="CONSOLE"/>
        </root>
    </springProfile>
</configuration>

相关问题