Configuring how exception stack traces appear in log entries using Log4J2
Sometimes it is required not to log exception stack traces or to limit the maximum depth of a stack trace that appears in application logs. This is true, for example, if you are using a commercial log aggregator and you have a limited quota per day and that quota is shared between multiple apps within your organization.
In Java, for example, it is possible for a stack trace to be easily more than 500 lines long. A couple of thousand of such exceptions could easily exceed your daily quota.
With Log4J2 it is easy to configure how stack traces appear in application logs. Three examples are in order.
Logging the exception message but swallowing the entire stack trace
# log4j2.yml
Configuration:
Appenders:
Console:
— name: NoStackTrace
target: SYSTEM_OUT
PatternLayout:
Pattern: “[%t] %-5level %logger{36} %msg — %ex{short.message} %n”
This will produce a log entry similar to:
[main] ERROR org.behrang.labs.Main An error occurred — I am thrown from a rogue method
Logging the exception message and the first line of its stack trace
# log4j2.yml
Configuration:
Appenders:
Console:
— name: FirstLineOfStackTrace
target: SYSTEM_OUT
PatternLayout:
Pattern: “[%t] %-5level %logger{36} %msg — %ex{short} %n”
This layout produces an output similar to:
[main] ERROR org.behrang.labs.Main An error occurred — java.lang.Exception: I am thrown from a rogue method
at org.behrang.labs.Main.rogueMethod(Main.java:22)
Logging the exception message and the first 5 lines of its stack trace
And finally:
#log4j2.yml
Configuration:
Appenders:
Console:
— name: FirstFiveLines
target: SYSTEM_OUT
PatternLayout:
Pattern: “[%t] %-5level %logger{36} %msg — %ex{5} %n”
will produce:
[main] ERROR org.behrang.labs.Main An error occurred — java.lang.Exception: I am thrown from a rogue method
at org.behrang.labs.Main.rogueMethod(Main.java:22)
at org.behrang.labs.Main.main(Main.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
For more options, see Log4J2 Layouts.