/*
*输出e.printStackTrace()的内容到log文件
*/
package c1;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.*;
public class Test{
public static void main(String[] args){
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd-HHmmss");
TestOut.sLogFileName=sdf.format(new Date())+".log";
try{
throw new Exception();
}
catch(Exception e){
//e.printStackTrace();
TestOut.logStackTrace(e);
}
TestOut.log("hello");
TestOut.log("hello1");
}
}
class TestOut{
public static String sLogFileName="";
public static void log(Object x){
System.out.println(x);
try{
BufferedWriter bw = new BufferedWriter( new FileWriter(sLogFileName,true));
bw.write(new Date()+" -- "+x);
bw.newLine();
bw.close();
//throw new IOException();
}
catch(IOException e){
e.printStackTrace();//System.out.println (e);
System.out.println("failed to write "+x+" into file:"+sLogFileName);// print out the runtime variables
System.exit(0); //terminate the program or Runtime.getRuntime().exit(0);
}
}
public static void logStackTrace(Exception e){
TestOut.log(e.toString());
StackTraceElement[] ste= e.getStackTrace();
int stelength=ste.length;
for(int i=0;i Object x=ste[i];
x=" "+x;
System.out.println(x);
try{
BufferedWriter bw = new BufferedWriter( new FileWriter(sLogFileName,true));
bw.write(x.toString());
bw.newLine();
bw.close();
//throw new IOException();
}
catch(IOException ioe){
ioe.printStackTrace();//System.out.println (e);
System.out.println("failed to write "+x+" into file:"+sLogFileName);// print out the runtime variables
System.exit(0); //terminate the program or Runtime.getRuntime().exit(0);
}
}
}
}
/*
输出结果:
java.lang.Exception
c1.Test.main(Test.java:13)
hello
hello1
log文件2010-01-18-102901.log内容:
Mon Jan 18 14:22:51 CST 2010 -- java.lang.Exception
c1.Test.main(Test.java:13)
Mon Jan 18 14:22:51 CST 2010 -- hello
Mon Jan 18 14:22:51 CST 2010 -- hello1
*/
阅读(4642) | 评论(0) | 转发(0) |