错误日志记载

本文的主要内容:利用Directory、Path、StreamWriter实现对错误记载的一个简单方法。

如果在多线程中,还需要加锁,来保证同步。本代码没有考虑同步的部分。

Log.cs

 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 using System.IO;
7 namespace y.LogExample
8 {
9 class Log
10 {
11 ///<summary>
12 /// 记载错误日志
13 ///</summary>
14 ///<param name="MethodName">出现错误的方法名</param>
15 ///<param name="ExceptionType">出现异常的名称如:ArgumentException 等</param>
16 ///<param name="ExceptionDetail">异常的描述</param>
17 publicstaticvoid Save(string MethodName,string ExceptionType,string ExceptionDetail)
18 {
19 string currentPath = AppDomain.CurrentDomain.BaseDirectory;
20 string folderPath = Path.Combine(currentPath, "ErrorLog");
21 if (!Directory.Exists(folderPath))
22 {
23 Directory.CreateDirectory(folderPath);
24 }
25 string logPath = Path.Combine(folderPath, DateTime.Now.ToShortDateString() +".log");
26 StreamWriter fw =new StreamWriter(logPath,true);//如果文件存在,则在文件后面直接添加文本;否则添加文件。
27 fw.WriteLine(string.Format("[{0}]\r\nMethod:{1}\r\n{2}:{3}\r\n",DateTime.Now.ToString(),MethodName,ExceptionType,ExceptionDetail));
28 fw.Flush();
29 fw.Close();
30 }
31 }
32 }

 

posted @ 2011-08-22 10:52  走过留痕  阅读(257)  评论(0编辑  收藏  举报