简体   繁体   English

如何使用 java 的 Logger class 记录堆栈跟踪

[英]How do I log a stacktrace using java's Logger class

I am using Java's Logger class. I want to pass ex.printStackTrace() into Logger.log(loglevel, String) , but printStackTrace() returns void .我正在使用 Java 的Logger class。我想将ex.printStackTrace()传递给Logger.log(loglevel, String) ,但printStackTrace()返回void So I am not able to pass and print the stack trace of the exception.所以我无法传递和打印异常的堆栈跟踪。

Is there any way that I can convert void into String , or are there any other methods to print the whole stack trace of exceptions?有什么方法可以将void转换为String ,或者是否有任何其他方法可以打印异常的整个堆栈跟踪?

You need to understand that void is actually nothingness .你需要明白void实际上是nothingness You cannot convert what is nothing.你不能转换什么都不是。 You might end up printing void as a string, but (trust me), you don't want that.您可能最终将void打印为字符串,但是(相信我),您不想要那样。

I think what you are looking for is我想你正在寻找的是

// assuming ex is your Exception object
logger.error(ex.getMessage(), ex);
// OR
Logger.log(errorLogLevel, ex.getMessage(), ex)

This will print the error message using the logger that you have configured.这将使用您配置的记录器打印错误消息。 For more details, you can take a look at the java docs for Exception#getMessage()有关更多详细信息,您可以查看Exception#getMessage()的 java 文档

使用java.util.logging.Logger#log(Level, String, Throwable)并传入ex作为第三个参数,如下所示:

LOGGER.log(Level.INFO, ex.getMessage(), ex);

Also another alternative would be:另一种选择是:

import org.apache.commons.lang3.exception.ExceptionUtils;

log.error("Exception : " + ExceptionUtils.getStackTrace(exception));

With below format you can have the stack trace:使用以下格式,您可以获得堆栈跟踪:

java.util.logging.SimpleFormatter.format=%1$tF %1$tT [%4$-7s][%2$s] %5$s %6$s%n

The point in this pattern is %6$s.此模式中的要点是 %6$s。 It will print the stack trace.它将打印堆栈跟踪。

You can't convert void into String ;您不能将void转换为String no such conversion exists.不存在这种转换。 void doesn't return anything back, so you have no value to retrieve. void不会返回任何内容,因此您没有任何价值可检索。

What you probably want to do is get the message of the exception instead via ex.getMessage() .您可能想要做的是通过ex.getMessage()获取异常消息。

There's an overloaded printStackTrace method that takes in a PrintWriter.有一个重载的printStackTrace 方法接收PrintWriter。

You can do something like this你可以做这样的事情

Writer buffer = new StringWriter();
PrintWriter pw = new PrintWriter(buffer);
ex.printStackTrace(pw);
Logger.log(loglevel, buffer.toString());

You can use the getStackTrace() method to get an array of StackTraceElements, and generate a String from there.您可以使用getStackTrace()方法获取 StackTraceElements 数组,并从那里生成一个字符串。 Otherwise, if just the final error message is sufficient, use the getMessage() method as suggested by Makoto.否则,如果只有最终的错误消息就足够了,请使用 Makoto 建议的getMessage()方法。

To get the stack trace as a String from an array of StackTraceElement objects, you need to iterate over the array (taken from JDK7 source):要从StackTraceElement对象数组中以String获取堆栈跟踪,您需要遍历该数组(取自 JDK7 源代码):

StringBuilder builder = new StringBuilder();
StackTraceElement[] trace = getOurStackTrace();
    for (StackTraceElement traceElement : trace)
        builder.append("\tat " + traceElement + "\n");

Another option is to use printStackTrace(PrintStream s) , where you get to specify where you want the stacktrace to be printed:另一种选择是使用printStackTrace(PrintStream s) ,您可以在其中指定要打印printStackTrace(PrintStream s)位置:

ByteArrayOutputStream out1 = new ByteArrayOutputStream();
PrintStream out2 = new PrintStream(out1);
ex.printStackTrace(out2);
String message = out1.toString("UTF8");

Thank you all.谢谢你们。 I am able to log the stack trace details using我能够使用记录堆栈跟踪详细信息

LOGGER.log(Level.INFO, ex.getMessage(),ex);
//ex is my exception object

You can use an ExceptionUtils if you need to see stacktrace without throwing Exception.如果你需要看到堆栈跟踪不抛出异常,您可以使用一个ExceptionUtils。

String stackTrace = ExceptionUtils.getStackTrace(new Exception("YourMessage"));
log.error(stackTrace);

As Makoto says, you probably want to do an ex.getMessage().正如 Makoto 所说,你可能想做一个 ex.getMessage()。

To further clarify, void means that there is nothing returned.进一步澄清, void意味着没有返回任何内容。 You can't cast nothing into something :)你不能把任何东西都投进去:)

you CAN convert stacktrace into String using below.您可以使用下面的方法将堆栈跟踪转换为字符串。 If e is the exception object如果e是异常对象

StringWriter stringWriter= new StringWriter();
PrintWriter printWriter= new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
String stackTraceAsString= stringWriter.toString(); 

You can also use ExceptionUtils from apache library or below log statement您还可以使用来自 apache 库或以下日志语句的 ExceptionUtils

    try{
      doSomething();
    }
    catch(Exception e){
    log.error("Exception in method doSomething ",e);
    }

The previous suggestions all seem to just put the stack trace in the log without prefixing each line with the logger details.之前的建议似乎都只是将堆栈跟踪放在日志中,而没有在每一行前面加上记录器详细信息。 My suggestion below processes the stack trace elements and formats each line as a logger line:我下面的建议处理堆栈跟踪元素并将每一行格式化为记录器行:

 log.error("{}", e.toString()); StackTraceElement[] stElements = e.getStackTrace(); log.error("(stacktrace) {}", e.toString()); for (StackTraceElement ste: stElements) { log.error("(stacktrace) at {}.{}({}.java:{})", new Object[] {ste.getClassName(), ste.getMethodName(), ste.getClassName(), ste.getLineNumber()}); } Throwable thisThrowable = e; boolean causedBy = true; while (causedBy) { Throwable throwable = thisThrowable.getCause(); if (throwable != null) { log.error("(stacktrace) Caused by: {}", throwable.toString()); stElements = throwable.getStackTrace(); for (StackTraceElement ste: stElements) { log.error("(stacktrace) at {}.{}({}.java:{})", new Object[] {ste.getClassName(), ste.getMethodName(), ste.getClassName(), ste.getLineNumber()}); } thisThrowable = throwable; // For the next caused-by check } else { log.error("(stacktrace) No Caused-by Exception"); causedBy = false; // No more caused-by Throwables, so end the loop } }

Each line of the stack trace is prefixed with "(stacktrace)".堆栈跟踪的每一行都以“(stacktrace)”为前缀。 This has the advantage of being able to filter them out when dumping log files, or to be able to find them easily.这样做的好处是能够在转储日志文件时将它们过滤掉,或者能够轻松找到它们。

With java.util.Arrays you can also solve this easily:使用 java.util.Arrays 你也可以轻松解决这个问题:

try {
    doSomething();
} catch (Exception e) {
    logger.error(Arrays.toString(e.getStackTrace()));
}

Arrays.toString(Object[] a) calls Object.toString() for each element or returns a String with "null" if the object is null. The elements are separated by a comma and a space. Arrays.toString(Object[] a) 为每个元素调用 Object.toString() 或如果 object 为 null 则返回带“null”的字符串。元素由逗号和空格分隔。 StackTraceElement implements toString(), so the array you get from e.getStackTrace() converts nicely. StackTraceElement 实现了 toString(),因此您从 e.getStackTrace() 获得的数组可以很好地转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM