日志记录

日志记录可结合上一专题的报告共同生成,日志中可记录自动化测试过程中详细日志信息.由日志中可以看到详细的报错时间,报错类,报错行,报错内容.
package ts.dw.logic;
 
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
 
/*
 * 日志类
 * 当运行遇到错误后会生成一个error的日志文件,方便查找问题
 */
public class ToLog {
 
	static GregorianCalendar time = new GregorianCalendar();
 
	//获取时间
	private static final String getToday = time.get(Calendar.YEAR)+"-"+(time.get(Calendar.MONTH)+1)+"-"+time.get(Calendar.DAY_OF_MONTH)+"-"+time.get(Calendar.HOUR_OF_DAY)+time.get(Calendar.MINUTE)+time.get(Calendar.SECOND)+"-";
 
	//日志名称由年月日时分秒组成
	private static final String filePath = "log\\"+getToday+"error.log";
 
	//写入文件
	public void toLog(String message){
		StackTraceElement stack[] = (new Throwable()).getStackTrace();
		StackTraceElement s = stack[1];
 
		//获取详细的出错位置
		String headerMessage = s.getClassName()+"."+s.getMethodName()+"()"+"★LineNum:"+s.getLineNumber()+"\r\nMessage:";
 
		//时间
		headerMessage = addDateTimeHeader(headerMessage);
		message = headerMessage + message + "\r\n";
 
		FileWriter fw = null;
		File file = null;
 
		//写文件
		try{
		    file = new File(filePath);
		    fw = new FileWriter(file,true);
		    fw.write(message);
		}catch(IOException ie){
		    ie.printStackTrace();
		}finally{
			try{
			    fw.close();
			}catch(IOException ie){
			    ie.printStackTrace();
			}
		}
	}
 
	//每条日志前加上当前时间
	@SuppressWarnings("deprecation")
	public String addDateTimeHeader(String headerMessage) {
		String dateTimeHeader = new Date().toLocaleString()+"★";
		return dateTimeHeader += headerMessage;
	}
 
	//测试函数
	public static void main(String args[]){
		ToLog log = new ToLog();
		for(int i=1;i<15;i++){
		    String message = "这只是测试"+i;
		    //需要写日志的地方只要如下调用该方法即可~
		    log.toLog(message);
		}
	}
}

你可能感兴趣的:(日志)