0

My application is using structured json logging and log4j. My goal is to add a new field to json log if a specific throwable is passed into log method as an argument

With mdc this is easy

} catch (SpecificException ex)
   MDC.put(key, ex.getData())
   logger.error("something bad happened", ex)
   MDC.remove(key)
} catch (OtherException ex) {
  logger.error("something bad happened", ex)
}

However I would prefer to find a solution that would work project wide possibly without mdc api optimally on a level of log appender. Is anything like this possible to achieve with log4j?

0

1 Answer 1

1

May I suggest you to try net.logstash.logback.argument.StructuredArguments

Here is the doc:

From there, you can try:

log.info("Your message {}", keyValue("key", yourValue));

which will produce something like:

{
  "@timestamp": "2019-04-17T18:27:01.099+02:00",
  "@version": "1",
  "message": "our message key=123",
  "logger_name": "MyApplication",
  "thread_name": "main",
  "level": "INFO",
  "level_value": 20000,
  "key": "123"
}

Or even something like:

log.info("Some object with ID {} is processed on {}.",
  StructuredArguments.fields(someObjectId),
  "someOtherArgument" // etc
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.