How to log formatted message, object array, exception?

Viewed 241470

What is the correct approach to log both a populated message and a stack trace of the exception?

logger.error(
    "\ncontext info one two three: {} {} {}\n",
    new Object[] {"1", "2", "3"},
    new Exception("something went wrong"));

I'd like to produce an output similar to this:

context info one two three: 1 2 3
java.lang.Exception: something went wrong
stacktrace 0
stacktrace 1
stacktrace ...

My SLF4J version is 1.6.1.

3 Answers

The accepted answer is great. I'm just adding here my case that is now working thanks for the answer. This may help someone else.

I'm using SLF4J and logback with a JSON encoder. Furthermore, I use marker and arguments to enrich my output.

    logger.error(getMarker("errorEvent"),
                 "An error occurred",
                 entries(mapOf("someKey" to "someValue")),
                 new Exception())

The output:

  {
   "level": "ERROR",
   "event": "errorEvent",
   "eventData": {
      "someKey": "someValue"
   },
   "stacktrace": "...omitted...",
   "message": "An error occurred"
}

Of course there is a lot of configuration of logstash behind the scenes, but I just wanted to show that the arguments passed as entries are shown in the configured eventData tag.

Related