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

I want to log INFO and higher level statements whenever the response code is >= 400 to capture as ma

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>


发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743859206a4519396.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信