How can I configure log4j to not print the excepti

2019-01-18 10:34发布

We use Log4j (and Commons Logging) to log our error messages. Now we want to set up an additional log appender that outputs fatal errors to syslog, but without the exceptionally long Java stacktraces (those will still be available in the full log file).

How would one configure this (using log4j.xml)? Is there a filter available to ignore the stack traces?

8条回答
萌系小妹纸
2楼-- · 2019-01-18 11:12

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

https://logging.apache.org/log4j/log4j-2.1/manual/layouts.html

查看更多
相关推荐>>
3楼-- · 2019-01-18 11:13

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

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

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

Ta-dum!

查看更多
成全新的幸福
4楼-- · 2019-01-18 11:20

Edit after reading some more of the source:

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

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

查看更多
放荡不羁爱自由
5楼-- · 2019-01-18 11:21

Here's the actual code I use:

import org.apache.log4j.PatternLayout;

public class NoStackTracePatterLayout extends PatternLayout {

 @Override
 public boolean ignoresThrowable(){
  return false;
 }
}
查看更多
forever°为你锁心
6楼-- · 2019-01-18 11:26

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

查看更多
闹够了就滚
7楼-- · 2019-01-18 11:27

In 1.2.16 you can use EnhancedPatternLayout

查看更多
登录 后发表回答