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 badges1 Answer
Reset to default -2Have 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")) >= 400</expression>
</evaluator>
<OnMatch>ACCEPT</OnMatch>
<OnMismatch>DENY</OnMismatch>
</filter>
</logger>
<root level="INFO">
<appender-ref ref="FILE"/>
</root>
</configuration>