把程序信息,日期,调用者信息都输出到一个日志文件是很有意义的事,有助于定位错误,获知程序运行状况,可观察到复现率低的bug。在java中有log4j,在C#中,自己写了一个简易的日志类,调用时用LogHelper.log("message");即可。日志输出到history.log。日志格式形如:
[ 2012-2-13 14:49:34 ]: ReadExcel2.Form1.buttonTestLog_Click() message!
[ 2012-2-13 14:49:35 ]: ReadExcel2.Form1.buttonTestLog_Click() message!
[ 2012-2-13 14:49:35 ]: ReadExcel2.Form1.buttonTestLog_Click() message!
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Reflection;
using System.Diagnostics;
namespace ReadExcel2
{
//日志类
class LogHelper
{
private static String logFileName = "history.log";
public static void log(String message)
{
if (!File.Exists(logFileName))
{
File.CreateText(logFileName);
}
using (StreamWriter sw = File.AppendText(logFileName))
{
//获取调用者的信息
StackTrace trace = new StackTrace();
MethodBase method = trace.GetFrame(1).GetMethod();
String methodInfo = method.DeclaringType.FullName + "." + method.Name + "()";
//输出日期、调用者信息、message
message = methodInfo + message;
String strDate = DateTime.Now.ToString();
sw.WriteLine("[ "+strDate+" ]: "+message);
}
}
}
}