自己寫的記錄日志,定期刪除日志的方法。
方法比較簡單,記錄一下吧。
/// <summary> /// 寫日志 /// </summary> /// <param name="strMsg">內容</param> /// <param name="strPath">路徑(相對hycom下的文件夾路徑)</param> /// <param name="fileName">日志名(默認yyyy-MM-dd.txt)</param> public static void WriteLog(string strMsg,string strPath,string fileName) { string path = AppDomain.CurrentDomain.BaseDirectory + strPath; if(!path.EndsWith("\\")||!path.EndsWith("/")) { path+="\\"; } if(!Directory.Exists(path)) { Directory.CreateDirectory(path); } DeleteLog(path); if(fileName=="") { fileName = DateTime.Now.ToString("yyyy-MM-dd")+".txt"; } if(!fileName.EndsWith(".txt")) { fileName+=".txt"; } try { //string fileName =DateTime.Now.ToString("yyyy-MM-dd") + ".txt"; StreamWriter sw = File.AppendText(path+fileName); sw.WriteLine("{0}:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"), strMsg); //sw.WriteLine("\n\r"); sw.Flush(); sw.Close(); } catch { } } /// <summary> /// 寫日志 /// </summary> /// <param name="strMsg">內容</param> /// <param name="strPath">路徑(相對hycom下的文件夾路徑)</param> public static void WriteLog(string strMsg,string strPath) { string fileName = DateTime.Now.ToString("yyyy-MM-dd")+".txt"; WriteLog(strMsg,strPath,fileName); } /// <summary> /// 定期刪除日志 /// </summary> /// <param name="strPath">日志路徑</param> private static void DeleteLog(string strPath) { if(Directory.Exists(strPath)) { DirectoryInfo dinfor = new DirectoryInfo(strPath); FileInfo[] files = dinfor.GetFiles(); foreach(FileInfo file in files) { try { //刪除創建日志日期是3個月前的日志 if(DateTime.Compare(file.CreationTime.AddMonths(3),DateTime.Now)<0) { file.Delete(); } //刪除最後修改日志日期是3個月前的日志 if(DateTime.Compare(file.LastWriteTime.AddMonths(3),DateTime.Now)<0) { file.Delete(); } //刪除日志名稱日期是3個月前的日志 if(DateTime.Compare(Convert.ToDateTime(file.Name.Substring(0,10)),DateTime.Now.AddMonths(-3))<0) { file.Delete(); } } catch(Exception ex) { continue; } } } }