日志记录

日志记录可结合上一专题的报告共同生成,日志中可记录自动化测试过程中详细日志信息.由日志中可以看到详细的报错时间,报错类,报错行,报错内容.
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);
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值