How to log exception stack trace in Json object with out breaking with log4j2
In the log4j Patternlayout
configuration you could use %enc{%ex}{CRLF}
which is replacing \n
and \r
with respectively \\n
and \\r
.
Applied to you sample:
{"a":"%X{Id}","b":"%d","message":"%m","priority":"%p","Exception":"%enc{%ex}{CRLF}"}
https://logging.apache.org/log4j/2.x/manual/layouts.html#PatternLayout
You could use the JSON library for this like so:
JSONObject object = new JSONObject();object.put("ID", idVariable);object.put("Exception", exceptionVariable);object.put("Priority", priorityVariable);object.toString();
or use :
object.toString(2);
for indentation (pretty print)
You can then use the object to pass it to a method for the Log4j logger
library for JSON found here JSON Library