For a Spring application I want to add a custom field to the log. Currently I use the default format but I want to add a custom field (category field) which should be present in all the logs:
W:Action D:2022-01-10 23:21:03.285 L:INFO C:c.h.l.LoggingDemoApplication F:StartupInfoLogger.java(61) Fn:logStarted T:main R: - Hello World
What are the best solution to add a custom field to the logback log?
What I studied until now are the following possible solutions:
Use marker. The disadvantage with this is that it's not scalable: if in future you need another custom field can't add another marker. Further based on some other posts the marker is best suited to mark special logs that need to be handle differently.
Use MDC.
Also using this it seems not the best solution because:
- It keeps the context so if there are multiple log statements in the same function, before each
logger.info()
there should beMDC.put("category", "action")
- The code becomes to verbose.
- It keeps the context so if there are multiple log statements in the same function, before each
Create a custom convertor (link). Get the arguments from the ILoggingEvent, get argument of 0. If this is the same type as category enum, then use it. The call for this is like
logger.info("Message here: {} {} {}", CatEnum.Action.getValue(), msg1, msg2, msg3)
.Create some static method in which the final format is generated. Pattern is similar to:
<pattern>%m%n</pattern>
To log, something like this should be used:
logger.info(customFormatter.fmtLog(CatEnum.Action.getValue(), msg))
. The returned value of fmtLog should be all the info from default logging + the category field.
Are there any built in solutions to add a custom field?