最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

logging - Spring Rest Log4j2.xml dynamic log level based on response code - Stack Overflow

programmeradmin3浏览0评论

I want to log INFO and higher level statements whenever the response code is >= 400 to capture as many log statements as possible. However, I don't want to flood the logs if the response code is < 400 (i.e., success).

We might need to asynchronously buffer logs based on the response code, as we don't know what the response code will be in advance. I have tried a few approaches but haven't been able to successfully get conditional log levels based on the response code to work.

Is there a way to achieve this? If so, could you provide any examples or references?

I want to log INFO and higher level statements whenever the response code is >= 400 to capture as many log statements as possible. However, I don't want to flood the logs if the response code is < 400 (i.e., success).

We might need to asynchronously buffer logs based on the response code, as we don't know what the response code will be in advance. I have tried a few approaches but haven't been able to successfully get conditional log levels based on the response code to work.

Is there a way to achieve this? If so, could you provide any examples or references?

Share Improve this question asked Apr 2 at 5:03 Arun GopalpuriArun Gopalpuri 2,50228 silver badges34 bronze badges
Add a comment  | 

1 Answer 1

Reset to default -2

Have you tried config use mdc and config it in logback.xml


public class ResponseLogger {
    private static final Logger logger = LoggerFactory.getLogger(ResponseLogger.class);

    public static void logWithResponseCode(int responseCode, String message) {
        MDC.put("responseCode", String.valueOf(responseCode));

        if (responseCode >= 400) {
            logger.info(message);
        } else {
            logger.debug(message);
        }

        MDC.remove("responseCode");
    }
}

<configuration>
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>logs/app.log</file>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <logger name="com.example" level="DEBUG">
        <filter class="ch.qos.logback.classic.filter.EvaluatorFilter">
            <evaluator>
                <expression>Integer.parseInt(mdc.get("responseCode")) &gt;= 400</expression>
            </evaluator>
            <OnMatch>ACCEPT</OnMatch>
            <OnMismatch>DENY</OnMismatch>
        </filter>
    </logger>

    <root level="INFO">
        <appender-ref ref="FILE"/>
    </root>
</configuration>


发布评论

评论列表(0)

  1. 暂无评论