0

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:

  1. 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.

  2. 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 be MDC.put("category", "action")
    • The code becomes to verbose.
  3. 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).

  4. 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?

florin
  • 719
  • 12
  • 31
  • MDC is static, I believe, so no, there doesn't need to be a put call before every log statement, only when you actually need to change the category, Your other solution is to imlpement your own logger methods/class – OneCricketeer Jan 10 '22 at 22:21
  • Yes, I agree to what you said regarding the put call. – florin Jan 11 '22 at 06:22

0 Answers0