如何将堆栈跟踪打印到页面?

时间:2013-06-22 07:17:54

标签: java jsp

如何将异常堆栈跟踪打印到网页?

import com.opensymphony.xwork2.ActionSupport;
import java.util.Arrays;

public class ExceptionAction extends ActionSupport 
{

 public String execute() 
 {      
    //
    String errMsg = Arrays.toString(Thread.currentThread().getStackTrace());

    this.addActionError(
                    "Unexcepted error has occurred. \n"
                    +errMsg
                    + "\nPlease try again or report this error to    administrator or support team. \n ");

    return "error";
 }

 /**
 * 
 */
 private static final long serialVersionUID = -3754090784536811052L;
}

但我使用上面的代码有一个无用的msg,msg是这样的:

    [java.lang.Thread.getStackTrace(Thread.java:1479),    com.monitoring.action.ExceptionAction.execute(ExceptionAction.java:11), sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method), sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39), 

2 个答案:

答案 0 :(得分:1)

请参阅documentation

File file = new File("test.log");
PrintStream ps = new PrintStream(file);
try {
    // something
} catch (Exception ex) {
    ex.printStackTrace(ps);
}
ps.close();

另见Difference between printStackTrace() and toString()

答案 1 :(得分:0)

以下是将堆栈跟踪打印到页面的代码

 package test;    
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

        PrintWriter out = response.getWriter();
        try {
            "test".charAt(20);
        } catch (RuntimeException e) {
            out.println("Stack Trace:<br/>");
            e.printStackTrace(out);
            out.println("<br/><br/>Stack Trace (for web display):</br>");
            out.println(displayErrorForWeb(e));
        }
    }

    public String displayErrorForWeb(Throwable t) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        t.printStackTrace(pw);
        String stackTrace = sw.toString();
        return stackTrace.replace(System.getProperty("line.separator"), "<br/>\n");
    }

}

来源:http://www.avajava.com/tutorials/lessons/how-do-i-display-a-stack-trace-on-a-web-page.html