Pages

Wednesday, April 13, 2011

Print the Stack Trace of the Exception to log file

In Java, when an Exception occurres , the following code snippent can be used to print it in a log file


import java.io.PrintWriter;
import java.io.StringWriter;
public static String logStackTrace(Throwable t)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
exp.printStackTrace(pw);
pw.flush();
sw.flush();
nLog("exception  "+ sw.toString());
}

public void nLog(String msg) {
try {
BufferedWriter out = new
BufferedWriter(new FileWriter("/home/temp/ex.log",true));
out.write(msg+"\n");
out.close();
} catch (IOException e) {
e.printStackTrace();
}

3 comments:

  1. Neil,

    You can directly pass in a logger and iterate through the StackTraceElement array returned by the getStackTrace() method of the Exception object.

    The java.util.logging.Logger object's logp() mthod can be use to print the sourceClass, sourceMethod, and the errorMessage.

    Sample code:

    StackTraceElement[] stacktraceElements = e.getStackTrace();
    StringBuffer buffer = new StringBuffer();
    buffer.append(e.getMessage()).append("\n");

    for (StackTraceElement stel: stacktraceElements) {
    buffer.append(e.toString()).append("\n");
    }

    logger.logp(Level.SEVERE, stacktraceElements[0].getClassName(),
    stacktraceElements[0].getMethodName(), buffer.toString());


    Note:
    a) logger is an object of an initialized/instantiated java.util.logging.Logger
    b) e is an object of a not null Exception

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete
  3. This comment has been removed by a blog administrator.

    ReplyDelete