java记录日志(异常记录)

/**测试**/
@Test
public void  test() throws Exception{
String msg = "success";
try{
int[] is = null;
System.out.println(is[10]);
}catch (Exception e) {
e.printStackTrace();
SimpleToof.setRecord(SimpleToof.getExceptionMsg(e));
msg = "fail";
}finally{
System.out.println(msg);
}

}


simpleToof.class

/**记录操作历史**/
public static void setRecord(String record){
String recordFilePath = "D://record/record"+getTypeDate("yyyy-MM-dd", new Date())+".txt";
System.out.println(recordFilePath);
File filename = new File(recordFilePath); 
try{
if (!filename.exists())  
filename.createNewFile(); 
FileWriter fileWriter = new FileWriter(recordFilePath, true); // true代表追加
fileWriter.write(getTypeDate("yyyyMMdd HH:mm:ss",new Date())+"\r\n"+record+"\r\n");
fileWriter.flush();
fileWriter.close();
}catch (Exception ex) {
ex.printStackTrace();
}
}


/**获取异常信息**/
public static String getExceptionMsg(Exception e){
StringBuffer emsg = new StringBuffer();
if(e!=null){
StackTraceElement[] st = e.getStackTrace();
for (StackTraceElement stackTraceElement : st) {
String exclass = stackTraceElement.getClassName();
String method = stackTraceElement.getMethodName();
emsg.append("[类:" + exclass + "]调用"+ method + "时在第" + stackTraceElement.getLineNumber()
      + "行代码处发生异常!异常类型:" + e.toString()+"\r\n");
}
}
return emsg.toString();
}

java记录日志(异常记录)_第1张图片


你可能感兴趣的:(JAVA学习笔记)