编写软件,难免会有一些异常,针对异常我们在实际的开发中相比都有一些,捕获异常的处理办法。把软件运行错误信息写成一个
错误日志文件很有必要。当我们在客户那边安装调试时就会更加快捷的,知道错误在哪里。否则你怎么知道软件运行哪里不正常,难道
还要在客户机器上装个开发环境调试一番吗?日志处理类,简单几行代码的事,不要手懒!
public class WriteLog
2 {
3 /// <summary>
4 /// 创建日志文件
5 /// </summary>
6 /// <param name="ex">异常类</param>
7 public static void CreateLog(Exception ex)
8 {
9 string path = Application.StartupPath+"\log";
10 if (!Directory.Exists(path))
11 {
12 //创建日志文件夹
13 Directory.CreateDirectory(path);
14 }
15 //发生异常每天都创建一个单独的日子文件[*.log],每天的错误信息都在这一个文件里。方便查找
16 path += "\"+DateTime.Now.ToShortDateString() + ".log";
17 WriteLogInfo(ex, path);
18 }
19 /// <summary>
20 /// 写日志信息
21 /// </summary>
22 /// <param name="ex">异常类</param>
23 /// <param name="path">日志文件存放路径</param>
24 private static void WriteLogInfo(Exception ex, string path)
25 {
26 using (StreamWriter sw = new StreamWriter(path, true, Encoding.Default))
27 {
28 sw.WriteLine("*****************************************【"
+ DateTime.Now.ToLongTimeString()
+ "】*****************************************");
29 if (ex != null)
30 {
31 sw.WriteLine("【ErrorType】" + ex.GetType());
32 sw.WriteLine("【TargetSite】" + ex.TargetSite);
33 sw.WriteLine("【Message】" + ex.Message);
34 sw.WriteLine("【Source】" + ex.Source);
35 sw.WriteLine("【StackTrace】" + ex.StackTrace);
36 }
37 else
38 {
39 sw.WriteLine("Exception is NULL");
40 }
41 sw.WriteLine();
42 }
43 }
44 }
复制代码