将旧版 e.printStractTrace() 记录到 log4j

发布于 2025-01-07 15:31:43 字数 1119 浏览 2 评论 0原文

我有一些遗留代码,其中有很多 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

幽梦紫曦~ 2025-01-14 15:31:43

您可以将标准 System.err 重定向到 log4j。

这个问题及其答案应该可以解决问题:

log4j 将 stdout 重定向到 DailyRollingFileAppender

如果可能的话,我仍然建议重写 printStacktrace 进入日志语句。

You can redirect the standard System.err to log4j.

This question and its answers should do the trick:

log4j redirect stdout to DailyRollingFileAppender

If possible though, I would still recommend to rewrite the printStacktrace's into log statements.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文