4

Environment

I have implemented log4j in my application successfully. I have used following pattern loayout:

{"a":"%X{Id}","b":"%d","message":"%m","priority":"%p","Exception":"%ex"}

It is logging as json format with my custom attributes.

But while logging exception with %ex it is printing whole trace, i want it but it is breaking json format.

Question

So can you please suggest me to put whole stack trace in json without breaking.

scott_lotus
  • 3,171
  • 22
  • 51
  • 69
Balaji
  • 151
  • 4
  • 15
  • Do you use the [JSON Layout](https://logging.apache.org/log4j/2.x/manual/layouts.html#JSONLayout) of Log4j2? – Robert Jan 06 '16 at 14:21
  • Why don't you raise this on the Log4j 2 issue tracker? https://issues.apache.org/jira/browse/LOG4J2 – Remko Popma Jan 06 '16 at 22:53

4 Answers4

2

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

Michele C.
  • 21
  • 2
0

StrackTrace contains new line chars.. which is probably breaking the JSON...why don't you use getMessage() instead.

Jason1
  • 101
  • 4
  • Hey thanks for your quick reply. but i am using log4j's pattern layout attributes(default). %ex to log whole exception(to identify everything where it happened ) so please let me know if u know any thing to remove new line chars. – Balaji Jan 06 '16 at 15:10
  • Did you get the answer? I am facing the same issue. – Sneha Jun 29 '20 at 11:03
0

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

Guido
  • 13
  • 5
  • Hey thanks for your quick reply. but i am using log4j's pattern layout attributes(default). %ex to log exception so i need any pre defined attributs to remove new line chars. – Balaji Jan 06 '16 at 15:08
0

This can be achieved using JSON encoding format %enc{%ex}{JSON}, replacing %ex.

Your pattern layout will look like this:

{"a":"%X{Id}","b":"%d","message":"%m","priority":"%p","Exception":"%enc{%ex}{JSON}"}

source: https://logging.apache.org/log4j/2.x/manual/layouts.html#PatternLayout

SharifS
  • 80
  • 2
  • 10