iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 11
0
自我挑戰組

IT人員面面觀系列 第 10

[C#]簡易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文字檔,如下圖:
https://ithelp.ithome.com.tw/upload/images/20181011/20107408nKsrFj8y1J.jpg


上一篇
[C#]將Xml字串轉成Data Table
下一篇
[SQL Server]資料的遮罩
系列文
IT人員面面觀28
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言