自己写的记录日志,定期删除日志的方法。
方法比较简单,记录一下吧。
1 /// <summary> 2 /// 写日志 3 /// </summary> 4 /// <param name="strMsg">内容</param> 5 /// <param name="strPath">路径(相对hycom下的文件夹路径)</param> 6 /// <param name="fileName">日志名(默认yyyy-MM-dd.txt)</param> 7 public static void WriteLog(string strMsg,string strPath,string fileName) 8 { 9 string path = AppDomain.CurrentDomain.BaseDirectory + strPath; 10 if(!path.EndsWith("\")||!path.EndsWith("/")) 11 { 12 path+="\"; 13 } 14 if(!Directory.Exists(path)) 15 { 16 Directory.CreateDirectory(path); 17 } 18 DeleteLog(path); 19 if(fileName=="") 20 { 21 fileName = DateTime.Now.ToString("yyyy-MM-dd")+".txt"; 22 } 23 if(!fileName.EndsWith(".txt")) 24 { 25 fileName+=".txt"; 26 } 27 try 28 { 29 //string fileName =DateTime.Now.ToString("yyyy-MM-dd") + ".txt"; 30 31 StreamWriter sw = File.AppendText(path+fileName); 32 33 sw.WriteLine("{0}:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"), strMsg); 34 //sw.WriteLine(" "); 35 sw.Flush(); 36 sw.Close(); 37 } 38 catch { } 39 } 40 /// <summary> 41 /// 写日志 42 /// </summary> 43 /// <param name="strMsg">内容</param> 44 /// <param name="strPath">路径(相对hycom下的文件夹路径)</param> 45 public static void WriteLog(string strMsg,string strPath) 46 { 47 string fileName = DateTime.Now.ToString("yyyy-MM-dd")+".txt"; 48 WriteLog(strMsg,strPath,fileName); 49 } 50 51 /// <summary> 52 /// 定期删除日志 53 /// </summary> 54 /// <param name="strPath">日志路径</param> 55 private static void DeleteLog(string strPath) 56 { 57 58 if(Directory.Exists(strPath)) 59 { 60 DirectoryInfo dinfor = new DirectoryInfo(strPath); 61 FileInfo[] files = dinfor.GetFiles(); 62 foreach(FileInfo file in files) 63 { 64 try 65 { 66 //删除创建日志日期是3个月前的日志 67 if(DateTime.Compare(file.CreationTime.AddMonths(3),DateTime.Now)<0) 68 { 69 file.Delete(); 70 } 71 //删除最后修改日志日期是3个月前的日志 72 if(DateTime.Compare(file.LastWriteTime.AddMonths(3),DateTime.Now)<0) 73 { 74 file.Delete(); 75 } 76 //删除日志名称日期是3个月前的日志 77 if(DateTime.Compare(Convert.ToDateTime(file.Name.Substring(0,10)),DateTime.Now.AddMonths(-3))<0) 78 { 79 file.Delete(); 80 } 81 } 82 catch(Exception ex) 83 { 84 continue; 85 } 86 } 87 } 88 }