Java – can I prefix each row of the stack trace in log4j?
•
Java
When you write
logger.error("message",exception);
Log4j generates a message and a complete stack trace:
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 ...
My conversion mode is
log4j.appender.syslog.layout.ConversionPattern=myPrefix: [%p] [%t] [%c] [%x] - %m%n
Then, can I use myprefix to prefix each row as follows:
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 ...
When I grep my log on myprefix, I can't see the stack trace We have many different prefixes (one for each module)
Thank you in advance
Solution
Subclass throwablerenderer, for example:
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; } }
Add to log4j properties:
log4j.throwableRenderer=whatever.package.LogThrowableRenderer
This uses the existing defaultthrowablerenderer to render stack traces in a familiar way before adding prefixes, so it will include throwable classes, messages, and reasons
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码