C#中使用列印日誌
阿新 • • 發佈:2019-01-09
在日常的工作中經常需要日誌,這樣能夠很容易定位到程式碼中的一些錯誤,.Net中有自帶的日誌介面。並沒有仔細去研究,這裡是我自己寫的日誌介面,記錄下來以便以後用到,根據時間列印相關的日誌檔案,程式碼如下:
namespace InspectionQueue.CommonHelper { public class LogInfoHelp { /// <summary> /// 日誌型別 /// </summary> private enum LOG_TYPE { LOG_FAIL= 0, //致命錯誤 LOG_ERROR, //一般錯誤 LOG_EXCEPTION, //異常 LOG_WARN, //警告 LOG_INFO, //一般資訊 } private StreamWriter LogFile = null; private static LogInfoHelp _instance = null; private string LogFilePath = null; public static LogInfoHelp GetInstance() { if(null == _instance) { _instance = new LogInfoHelp(); } return _instance; } private LogInfoHelp() { } /// <summary> /// 建立日誌檔案 /// </summary>public void CreateLogFile() { //獲取執行程式的路徑 string logFilePath = AppDomain.CurrentDomain.BaseDirectory; string logFileName = (DateTime.Now.Year).ToString() + '-' + (DateTime.Now.Month).ToString() + '-' + (DateTime.Now.Day).ToString() + "_Log.log"; logFilePath += "logFile\\"; if (!Directory.Exists(logFilePath)) { Directory.CreateDirectory(logFilePath); } this.LogFilePath = logFilePath + logFileName; } /// <summary> /// 資訊寫入日誌 /// </summary> /// <param name="strMsg"></param> public void WriteInfoToLogFile(string strLogInfo, ConstValues.LOG_TYPE logType) { LogFile = new StreamWriter(LogFilePath, true);//檔案儲存位置 string strlogInfo = null; switch(logType) { case ConstValues.LOG_TYPE.LOG_FAIL: { strlogInfo = String.Format("[{0}] 致命錯誤:{1}", DateTime.Now.ToString(), strLogInfo); } break; case ConstValues.LOG_TYPE.LOG_ERROR: { strlogInfo = String.Format("[{0}] 一般錯誤:{1}", DateTime.Now.ToString(), strLogInfo); } break; case ConstValues.LOG_TYPE.LOG_EXCEPTION: { strLogInfo = String.Format("[{0}] 異常:{1}", DateTime.Now.ToString(), strLogInfo); } break; case ConstValues.LOG_TYPE.LOG_WARN: { strLogInfo = String.Format("[{0}] 警告:{1}", DateTime.Now.ToString(), strLogInfo); } break; case ConstValues.LOG_TYPE.LOG_INFO: { strLogInfo = String.Format("[{0}] 一般資訊:{1}", DateTime.Now.ToString(), strLogInfo); } break; } LogFile.WriteLine(strLogInfo); LogFile.Close(); } } }