项目里打印日志用的 org.jboss.logging.Logger,在Linux上用nohup java -jar 启动的jar包,发现程序抛异常的时候只有在nohup.out里打印,在log.txt文件里没有打印,所以把Exception的堆栈信息转成String打印到logger里,查询了一些资料,整理了下。
方法一:用PrintWriter处理
package com.getexception;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
*
* TODO
* @author XWF
*/
public class GetErrorInfoFromException {
public static String getErrorInfoFromException(Exception e) {
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String s = sw.toString();
sw.close();
pw.close();
return "\r\n" + s + "\r\n";
} catch (Exception ex) {
return "获得Exception信息的工具类异常";
}
}
}
方法二:自己拼
package com.getexception;
/**
*
* TODO
* @author XWF
*/
public class GetExceptionInfo {
public static String GetException(Throwable e) {
try {
String s = e.toString()+"\n";
StackTraceElement[] trace = e.getStackTrace();
for (StackTraceElement traceElement : trace)
s = s + "\tat " + traceElement + "\n";
for (Throwable se : e.getSuppressed())
s = s + GetException(se);
Throwable ourCause = e.getCause();
if (ourCause != null)
s = s + GetException(ourCause);
s += "\n";
return s;
}catch (Exception exception) {
exception.printStackTrace();
return "GetExceptionInfo工具异常。";
}
}
}
测试Demo:
package com.getexception;
public class TestGetException {
public static void main(String[] args) {
try {
new AtestGetException().throwFromBtest();
}catch (Exception e) {
System.out.println(GetExceptionInfo.GetException(e));
System.out.println(GetErrorInfoFromException.getErrorInfoFromException(e));
}
}
}
class AtestGetException{
BtestGetException bGetException = new BtestGetException();
public void throwFromBtest() {
bGetException.throwException();
}
}
class BtestGetException{
public void throwException() {
Integer.parseInt("a");
}
}
结果: