C# 寫一個簡單LOG紀錄匯出TXT檔

  • 71
  • 0

透過基本讀寫檔案,製作簡易版本LOG記錄程式

目前有很多很棒的LOG紀錄的套件,但我只是想單純應用輸出且有時候還有政策問題,因此就採取自己造一個來用用

透過之前上課學習到CallerMemberNameAttribute 類別 這個類別,可以替此次造一個LOG程式碼,減少傳遞參數項目

主要函式
傳遞參數,每份LOG設置檔案大小、放置位置、檔案名稱,這樣就可以產生一個LOG的TXT設置

private static void init(string CallName, string LogMsg, string FileCatalog)
        {
            string strLogPath = string.Empty;
            string strTxtPath = string.Empty;
            int threshold = 6940000;

            strLogPath = string.Format("{0}{1}", ConfigurationSettings.AppSettings["LogConfigFile"], ConfigurationSettings.AppSettings["LoggerName"]);
            if (!Directory.Exists(strLogPath)) Directory.CreateDirectory(strLogPath);
            strTxtPath = string.Format("{0}\\{1}_{2}.txt", strLogPath, FileCatalog, System.DateTime.Now.ToString("yyyyMMdd", System.Globalization.DateTimeFormatInfo.InvariantInfo));

            FileInfo fileinfo = new FileInfo(strTxtPath);
            if (fileinfo.Exists && fileinfo.Length > threshold)
            {
                int count = 1;
                while (File.Exists(strTxtPath))
                {
                    strTxtPath = string.Format("{0}\\{1}_{2}_{3}.txt", strLogPath, FileCatalog, System.DateTime.Now.ToString("yyyyMMdd", System.Globalization.DateTimeFormatInfo.InvariantInfo), count);
                    count++;
                }
            }

            try
            {
                using (StreamWriter sw = new StreamWriter(strTxtPath, true, Encoding.UTF8, LogMsg.Length))
                {
                    sw.WriteLine(string.Format("[{0}]_[{1}]:{2}", System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), CallName, LogMsg));
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
        }
        
          private static string GetFileCatalog(string FileCatalog, string defaultValue)
        {
            if (!string.IsNullOrWhiteSpace(FileCatalog))
            {
                return FileCatalog + "_" + defaultValue;
            }
            else
            {
                return defaultValue;
            }
        }

 


應用函式-就只區分一般LOG紀錄跟ERRLOG紀錄,若要更多細分,也是可以重新規劃,利用

public static void WriteInfo(string LogMsg, string FileCatalog = null, [CallerMemberName]  string CallName = "")
        {
            FileCatalog = GetFileCatalog(FileCatalog, "WriteInfo");
            init("CallerMemberName: " + CallName, LogMsg, FileCatalog);
        }

        public static void WriteError(string LogMsg, string FileCatalog = null, [CallerMemberName]  string CallName = "")
        {
            FileCatalog = GetFileCatalog(FileCatalog, "WriteError");
            init("CallerMemberName: " + CallName, LogMsg, FileCatalog);
        }

有時做批次處理等,錯誤卻是在被使用者通知缺少或發生問題才知道,某一個執行區間發生錯誤,這時再來找檔案錯誤,有點慢!!

既然已知路徑,可以在執行完成,檢查有沒有產生ERRLOG檔,有就發信將檔案寄給相關人員,至少當天發生錯誤,在即時內被看到。