記錄日誌檔案

taogchan發表於2013-09-13


    class CommonFuc
    { 
  private static readonly string strLogPath = System.Configuration.ConfigurationSettings.AppSettings["logPath"];//日誌路徑

        ///


        /// 用於記錄日誌
        ///

        /// 日誌path
        /// 日誌內容
        public static void WriteLog(string logType, string logInfo)
        {
            string filename = string.Empty;
            switch (logType)
            {
                case "MailLog":
                    filename = strLogPath + @"\MailLogs\" + DateTime.Now.ToString("yyyyMMdd") + "-Notes.log"; ;
                    break;
                case "RuningLog":
                    filename = strLogPath + @"\ServiceLogs\" + DateTime.Now.ToString("yyyyMMdd") + "--B2CService.log";
                    break;
            }
            FileInfo f = new FileInfo(filename);
            FileStream fs = null;
            StreamWriter sw = null;
            Monitor.Enter(typeof(CommonFuc));
            try
            {
                if (f.Exists)
                {
                    fs = new FileStream(filename,FileMode.Append, FileAccess.Write, FileShare.Write);
                }
                else
                {
                    fs = new FileStream(filename,FileMode.Create, FileAccess.Write, FileShare.Write);
                }
                sw = new StreamWriter(fs);
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss :") + logInfo);
                sw.Flush();
            }
            catch (IOException e)
            {

            }
            finally
            {
                sw.Close();
                fs.Close();
                Monitor.Exit(typeof(CommonFuc));
            }
        }

        ///


        /// DELETE LOG
        ///

        ///
        public static void DeleHistoryLog(double days)
        {
            string del = "ServiceLogs,MailContent1,MailLogs";
            foreach (string item in del.Split(','))
            {
                DirectoryInfo dir = new DirectoryInfo(strLogPath + @"\" + item);
                FileInfo[] files = dir.GetFiles();
                foreach (FileInfo f in files)
                {
                    if (DateTime.Now.AddDays(days).CompareTo(f.CreationTime) > 0)
                    {
                        f.Delete();
                    }
                }
            } 
        }
}
 //在config中新增路徑
 
 <!--日誌路徑--&gt
   
 

//呼叫

            catch (Exception ex)
            {
                CommonFuc.WriteLog("RuningLog", "異常======>>" + ex.Message + "  SP======>>" + "pk_automial.p_show_mail_info");
            }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/22392018/viewspace-772685/,如需轉載,請註明出處,否則將追究法律責任。

相關文章