Issue
In my SpringBoot app I use CommonsRequestLoggingFilter to log all my incomming requests and it works fine :
CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter() {
@Override
protected boolean shouldLog(HttpServletRequest request) {
}
@Override
protected void beforeRequest(HttpServletRequest request, String message) {
}
@Override
protected void afterRequest(HttpServletRequest request, String message) {
this.logger.debug(message);
}
};
But to make debugging easier in a Kibana environnement, i would to like to append several information to the core log. At other places in my code I use StructuredArguments
like this and it works fine :
this.logger.debug(message, keyValue("foo","bar"));
But inside CommonsRequestLoggingFilter the logger used is org.apache.commons.logging.Log, that is not letting me add any parameter to my log.
Is there any way to override the logger used in CommonsRequestLoggingFilter ? Or other ideas ?
Thanks a lot
Solution
You cannot override the logger
in CommonsRequestLoggingFilter
because it is final.
You have at least two options.
The first one is to create a new class that extends AbstractRequestLoggingFilter
and use it instead of CommonsRequestLoggingFilter
. In this new class you can do what you wish like :
org.slf4j.Logger yourLogger = LoggerFactory.getLogger("MyRequestLoggingFilter");
...
@Override
protected void afterRequest(HttpServletRequest request, String message) {
yourLogger.debug(message, keyValue("foo","bar"));
}
To continue to use everything as it is you can use MDC
, to add new key/values to the logger. It is not the same thing, but it will log the values. You can, for example extend CommonsRequestLoggingFilter
and put the values in MDC, or in each "context" add the values, so the logger will log them.
Example if extending CommonsRequestLoggingFilter
:
@Override
protected void afterRequest(HttpServletRequest request, String message) {
MDC.put("orderId", "123");
super.afterRequest(request, message);
MDC.remove("orderId");
}
If using JSON logger the aspect will be more or less this one:
{
...
"message": "Some message",
...
"orderId": "123"
}
The samples were taken from the next link, where you can also get more details: https://www.innoq.com/en/blog/structured-logging/
Answered By - pringi
Answer Checked By - Timothy Miller (JavaFixing Admin)