English 中文(简体)
Java - 需要一个能记录堆栈跟踪信息的日志记录包。
原标题:Java - Need a logging package that will log the stacktrace
  • 时间:2010-02-25 06:26:09
  •  标签:
  • java
  • logging

Is there a Logger that will easily log my stacktrace (what I get with ex.printStackTrace())? I ve searched the log4j docs and found nothing about logging the stacktrace.

我可以自己做这件事。

StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
logger.error(stacktrace);

但我不想在各处复制此代码。

If log4j won t do this for me is there another logging package that will log the stacktrace for me?

谢谢。

最佳回答

使用 log4j 可以完成此操作:

logger.error("An error occurred", exception);

第一个参数是要显示的消息,第二个参数是被记录堆栈跟踪的异常(可抛出的)。

另一个选择是commons-logging,这里也是一样的:

log.error("Message", exception);

利用java.util.logging可以进行此操作:

logger.log(Level.SEVERE, "Message", exception);
问题回答

java.util.logging中,您可以像这样使用自定义日志格式化程序初始化记录器:

private Logger initTextLogger() throws SecurityException, IOException {
        Logger logger = Logger.getLogger(YourClass.class.getName());
        FileHandler fileHandler = new FileHandler(logFilePath, false);
        SimpleFormatter logFormatter = new SimpleFormatter() {
            @Override
            public String format(LogRecord record) {
            String stacktrace = "";
            Throwable t = record.getThrown();
            if(t!=null){
                StringWriter sw = new StringWriter();
                t.printStackTrace(new PrintWriter(sw));
                stacktrace = sw.toString();
            }               
            return record.getLevel() + ": " + record.getMessage() + "
"
                    + stacktrace;
        }
        };
        fileHandler.setFormatter(logFormatter);
        logger.addHandler(fileHandler);

        return logger;
    }




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签