将旧版 e.printStractTrace() 记录到 log4j
我有一些遗留代码,其中有很多 e.printStackTrace()
,由于明显的原因,这些代码没有打印在 log4j 文件中。最新的代码确实有 log.error("Exception returned in class::method",e);
。是否有一种标准方法可以在 log4j 中记录这些遗留的 e.printStackTrace()
?
这是我的 log4j.properties。 中设置属性文件/日志文件名
PropertyConfigurator.configure("log4j.properties");
setLog4jFile("log.txt");
private static void setLog4jFile(String logFileName) {
try {
Logger rootLogger = Logger.getRootLogger();
RollingFileAppender appender = new RollingFileAppender(new PatternLayout("%p %t %c - %m%n"), logFileName, false);
appender.setMaxFileSize("10000KB");
appender.setMaxBackupIndex(10);
rootLogger.addAppender(appender);
}catch (Exception e) {
e.printStackTrace();
}
}
我正在代码log4j.properties
log4j.rootCategory=info, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F%L) - %m%n
I have some legacy code where there are lot of e.printStackTrace()
, those are not printed in log4j file for obvious reasons. The latest code does have log.error("Exception occured in class::method",e);
. Is there a standard way of logging those legacy e.printStackTrace()
in log4j?
Here is my log4j.properties. I am setting up the property file/log file name within the code
PropertyConfigurator.configure("log4j.properties");
setLog4jFile("log.txt");
private static void setLog4jFile(String logFileName) {
try {
Logger rootLogger = Logger.getRootLogger();
RollingFileAppender appender = new RollingFileAppender(new PatternLayout("%p %t %c - %m%n"), logFileName, false);
appender.setMaxFileSize("10000KB");
appender.setMaxBackupIndex(10);
rootLogger.addAppender(appender);
}catch (Exception e) {
e.printStackTrace();
}
}
log4j.properties
log4j.rootCategory=info, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F%L) - %m%n
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将标准
System.err
重定向到 log4j。这个问题及其答案应该可以解决问题:
如果可能的话,我仍然建议重写
printStacktrace
进入日志语句。You can redirect the standard
System.err
to log4j.This question and its answers should do the trick:
If possible though, I would still recommend to rewrite the
printStacktrace
's into log statements.