日志记录功能

给自己的程序,加上记录日志的功能。 

以下是C#代码,可以直接复制使用的。

 

 1 using System; 
 2 using System.Collections.Generic; 
 3 using System.Text; 
 4 using System.IO; 
 5   
 6 namespace PingMock 
 7 { 
 8     class LogClass 
 9     { 
10          /**//// <summary> 
11          /// 写入日志文件 
12          /// </summary> 
13          /// <param name="input"></param> 
14          public void WriteLogFile(string input) 
15         { 
16             /**/
17             ///指定日志文件的目录 
18             string fname = Directory.GetCurrentDirectory() + "\\LogFile.txt"; 
19             /**/
20             ///定义文件信息对象 
21   
22             FileInfo finfo = new FileInfo(fname); 
23   
24             if (!finfo.Exists) 
25             { 
26                 FileStream fs; 
27                 fs = File.Create(fname); 
28                 fs.Close(); 
29                 finfo = new FileInfo(fname); 
30             } 
31   
32             /**/
33             ///判断文件是否存在以及是否大于2K 
34             if (finfo.Length > 1024 * 1024 * 10) 
35             { 
36                 /**/
37                 ///文件超过10MB则重命名 
38                 File.Move(Directory.GetCurrentDirectory() + "\\LogFile.txt", Directory.GetCurrentDirectory() + DateTime.Now.TimeOfDay + "\\LogFile.txt"); 
39                 /**/
40                 ///删除该文件 
41                 //finfo.Delete(); 
42             } 
43             //finfo.AppendText(); 
44             /**/
45             ///创建只写文件流 
46   
47             using (FileStream fs = finfo.OpenWrite()) 
48             { 
49                 /**/
50                 ///根据上面创建的文件流创建写数据流 
51                 StreamWriter w = new StreamWriter(fs); 
52   
53                 /**/
54                 ///设置写数据流的起始位置为文件流的末尾 
55                 w.BaseStream.Seek(0, SeekOrigin.End); 
56   
57                 /**/
58                 ///写入“Log Entry : ” 
59                 w.Write("\n\rLog Entry : "); 
60   
61                 /**/
62                 ///写入当前系统时间并换行 
63                 w.Write("{0} {1} \n\r", DateTime.Now.ToLongTimeString(), 
64                     DateTime.Now.ToLongDateString()); 
65   
66                 /**/
67                 ///写入日志内容并换行 
68                 w.Write(input + "\n\r"); 
69   
70                 /**/
71                 ///写入------------------------------------“并换行 
72                 w.Write("------------------------------------\n\r"); 
73   
74                 /**/
75                 ///清空缓冲区内容,并把缓冲区内容写入基础流 
76                 w.Flush(); 
77   
78                 /**/
79                 ///关闭写数据流 
80                 w.Close(); 
81             } 
82               
83         } 
84     } 
85 } 
posted on 2013-02-05 12:39  yj_smile  阅读(299)  评论(0编辑  收藏  举报