当你写作
logger.error("message",exception);
log4j生成消息和完整的堆栈跟踪:
Aug 9 06:26:13 10.175.60.14 myPrefix: [error] [TP-Processor114] [my.class.Name] message : exception at fatherOfException at fatherof_fatherOfException at fatherof_fatherof_fatherOfException ...
我的转换模式是
log4j.appender.syslog.layout.ConversionPattern=myPrefix: [%p] [%t] [%c] [%x] - %m%n
那么,是否可以使用myPrefix为每一行添加前缀,如下所示:
Aug 9 06:26:13 10.175.60.14 myPrefix: [error] [TP-Processor114] [my.class.Name] message : exception myPrefix at fatherOfException myPrefix at fatherof_fatherOfException myPrefix at fatherof_fatherof_fatherOfException ...
当我在myPrefix上grep我的日志时,我看不到堆栈跟踪.我们有许多不同的前缀(每个模块一个)
提前致谢.
解决方法
子类ThrowableRenderer,例如:
import org.apache.log4j.DefaultThrowableRenderer; import org.apache.log4j.spi.ThrowableRenderer; public class LogThrowableRenderer implements ThrowableRenderer { DefaultThrowableRenderer def = new DefaultThrowableRenderer(); @Override public String[] doRender(Throwable t) { String[] temp = def.doRender(t); for (int i = 0; i < temp.length; i++) { temp[i] = "myPrefix "+temp[i]; } return temp; } }
添加到log4j.properties:
log4j.throwableRenderer=whatever.package.LogThrowableRenderer
这使用现有的DefaultThrowableRenderer在添加前缀之前以熟悉的方式呈现堆栈跟踪,因此它将包括Throwable类,消息和原因.