2017年9月1日 星期五

[筆記]簡易Log method

程式中經常會遇到許多需要紀錄log的部份,有些是透過套件(如:Log4Net)來實作,小弟介紹的是簡易log method,其程式碼如下:
#region 寫入Log
/// 
///message:紀錄文字
///
public void LogWrite(string message)
{   
    string FilePath = ConfigurationSettings.AppSettings["LogDir"].ToString();    
     //從config檔抓取LogDir參數的值 
    string fileName = FilePath + string.Format("\\{0:yyyy}\\{0:MM}\\{0:yyyy-MM-dd}.txt", DateTime.Now);
    //設定檔案名稱,格式為西元年-月-日.txt  
    FileInfo fileInfo = new FileInfo(fileName);   
    if (fileInfo.Directory.Exists == false)
    {
        fileInfo.Directory.Create();
        //若無此檔案則新增
    }
    string writeString = string.Format("{0:yyyy/MM/dd HH:mm:ss.fff} {1}",DateTime.Now, message) + Environment.NewLine;
    File.AppendAllText(fileName, writeString, Encoding.Unicode);
    
}
#endregion
此method會依年、月建立目錄並產生每日log文字檔,如下圖:

以上介紹,各位如有任何意見,歡迎留言指教!

沒有留言:

張貼留言

[SQL Server]主動通知SQL Server發生錯誤的機制

當SQL Server有特定錯誤發生時,管理人員也沒有時間經常去查看SQL Server錯誤檔, 於是有時特定錯誤可能很重要時,但卻沒有人被通知到,現在小弟實作一個主動通知的機制。 首先先新增警示,在這裡選擇想要被通知的錯誤訊息的等級或其它設定 接著在回應頁籤中,勾選執...