[ACCEPTED]-How can I configure log4j to not print the exception stacktrace?-log4j

Accepted answer
Score: 17

Edit after reading some more of the source:

You 7 still need to subclass PatternLayout, but 6 the method you want to override is ignoresThrowable(): it 5 should return false, which will prevent 4 the appender from writing the Throwable 3 (it assumes that the layout has done so 2 already).

No way to specify this in the configuration: PatternLayout 1 has a hardcoded "return true".

Score: 11

Here's the actual code I use:

import org.apache.log4j.PatternLayout;

public class NoStackTracePatterLayout extends PatternLayout {

 public boolean ignoresThrowable(){
  return false;


Score: 9

If you use log4j > 1.2.16, you can use 3 the EnhancedPatternLayout layout.

Example (with a log4j.properties 2 file), define it as the layout of your appender, and 1 then add %throwable{0} in the conversion pattern:

log4j.appender.XXX.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c:%L - %m%n%throwable{0}
Score: 6

In 1.2.16 you can use EnhancedPatternLayout


Score: 4

As of Log4j2, you can just add "%ex{0}" to your 1 log pattern (assuming you're using PatternLayout)


Score: 2

The "nopex" or "nopexception" conversion 6 word in logback-classic (log4j's successor) disables 5 printing stack traces. The "nopex" conversion 4 word is documented along with the rest of conversion words. You 3 need to scroll down a little.

If you need 2 further information on this topic, please 1 contact the logback-user mailing list.

Score: 1

You may need to write a custom layout to 2 do it (which isn't that bad to do; you could 1 subclass PatternLayout).

Score: 0

If you can change the source code, then 19 another option is available for consideration.

In 18 my applications, I always and only log FATAL 17 messages from my applications entry point 16 (e.g., "main()"), since I only know that 15 they are fatal if I am about to exit the 14 application because of them.

Therefore, in 13 this one place (or handful if you have multiple 12 application entry points), instantiate a 11 Log4j Logger with a special class or MDC 10 of "syslog" or similar. Upon catching a 9 soon-to-be-FATAL error, log it in the usual 8 way (for your other log files and such), but 7 also invoke the fatal() method on this new 6 "syslog" Logger with only the precise message 5 that you want (such as only the exception 4 class and message but without the stack 3 trace). Then configure Log4j to direct 2 only this "syslog" class or MDC to a newly-configured 1 Appender that targets the SysLog.


More Related questions