C# Debug執行日誌Logs的實現

TA遠方發表於2019-07-25

一, 建立一個Logs的類,日誌記錄的實現

public class Logs
    {
        private static object lockObj = new object();

        private static int errCount = 0;

        public static void WriteLog(string msg, List<string> cacheText, Exception ex)
        {
            var frame = new StackTrace().GetFrame(1);
            string code = $"{frame.GetMethod().ReflectedType}.{frame.GetMethod().Name}\r\n\t";
            cacheText.Add($"{DateTime.Now.AddHours(app_base_data.static_time_diff).ToString("mm分ss秒")} Excetion Msg:{ex.Message}\r\n\tST:{ex.StackTrace}\r\n\t{code}{msg}");
        }

        public static void WriteLog(string msg, List<string> cacheText)
        {
            cacheText.Add(string.Format("{0}\t{1}\r\n", DateTime.Now.AddHours(app_base_data.static_time_diff).ToString("mm分ss秒"), msg));
        }

        public static void WriteLog(LogType type, string msg)
        {
            lock (lockObj)
            {
                try
                {
                    string pdir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
                    if (!Directory.Exists(pdir))
                    {
                        Directory.CreateDirectory(pdir);
                    }

                    string dir = Path.Combine(pdir, type.ToString());
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }

                    string path = Path.Combine(dir, DateTime.Now.AddHours(app_base_data.static_time_diff).ToString("yyyyMMddHH") + ".txt");
                    File.AppendAllText(path, string.Format("{0}\t{1}\r\n", DateTime.Now.AddHours(app_base_data.static_time_diff).ToString("yyyy-MM-dd HH:mm:ss"), msg), Encoding.UTF8);
                    if (errCount > 0) errCount = 0;
                }
                catch (Exception e)
                {
                    if (errCount < 100)
                    {
                        string pdir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logsWriteErr.txt");
                        File.AppendAllText(pdir, $"日誌輸出異常! msg:{e.Message}  st:{e.StackTrace}");
                        errCount++;
                    }
                }
            }
        }
        
        public static void printflnCache(LogType type, List<string> cacheText)
        {
            if (cacheText.Count < 2) return;
            var sb = new StringBuilder();
            foreach (var t in cacheText)
            {
                if (string.IsNullOrEmpty(t)) continue;
                sb.Append(t);
            }
            sb.Append($"\r\n┗━━━{DateTime.Now.AddHours(app_base_data.static_time_diff).ToString("mm分ss秒")}┅END");

            //Console.Write(sb.ToString());
            lock (lockObj)
            {
                try
                {
                    string pdir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
                    if (!Directory.Exists(pdir))
                    {
                        Directory.CreateDirectory(pdir);
                    }

                    string dir = Path.Combine(pdir, type.ToString());
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }

                    string path = Path.Combine(dir, DateTime.Now.AddHours(app_base_data.static_time_diff).ToString("yyyyMMddHH") + ".txt");
                    File.AppendAllText(path, sb.ToString(), Encoding.UTF8);
                }
                catch (Exception e)
                {
                    if (errCount < 100)
                    {
                        string pdir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logsWriteErr.txt");
                        File.AppendAllText(pdir, $"日誌輸出異常! msg:{e.Message}  st:{e.StackTrace}");
                        errCount++;
                    }
                }
            }

            cacheText.Clear();
            sb.Clear();
            cacheText = null;
            sb = null;
        }

        public static List<string> createPrintflnLogsCache(string v="")
        {
            var logs = new List<string>();
            logs.Add($"\r\n┏━━━{DateTime.Now.AddHours(app_base_data.static_time_diff).ToString("mm分ss秒")}┅{v}");
            return logs;
        }

        /// <summary>
        /// clear old timeout logs file
        /// </summary>
        /// <param name="timeout day"></param>
        public static void clearTimeoutLogsFIles(int day=7)
        {
            var minDt = DateTime.Now.AddHours(app_base_data.static_time_diff).AddDays(0-day);
            var names = Enum.GetNames(typeof(LogType));
            var pdir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
            var fileReg = new Regex("\\d{10}(?=.txt$)");
            foreach (var name in names)
            {
                var dir = Path.Combine(pdir, name);
                if (!Directory.Exists(dir)) continue;
                var files = Directory.GetFiles(dir);
                foreach (var file in files)
                {
                    //yyyyMMddHH.txt
                    var m = fileReg.Match(file);
                    if (!m.Success) continue;
                    var dt = DateTime.ParseExact(m.Value, "yyyyMMddHH", CultureInfo.CurrentCulture);
                    if (dt >= minDt) continue;
                    File.Delete(file);
                    Logs.WriteLog(LogType.Info, $"刪除了過期日誌檔案{file}");
                }
            }
        }

        public static void WriteWordLog(LogType type, string msg)
        {
            lock (lockObj)
            {
                try
                {

                    string pdir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
                    if (!Directory.Exists(pdir))
                    {
                        Directory.CreateDirectory(pdir);
                    }

                    string dir = Path.Combine(pdir, type.ToString());
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }

                    string path = Path.Combine(dir, DateTime.Now.AddHours(app_base_data.static_time_diff).ToString("yyyyMMddHH") + ".txt");
                    File.AppendAllText(path, msg, Encoding.UTF8);

                    if (errCount > 0) errCount = 0;
                }
                catch (Exception e)
                {
                    if (errCount < 100)
                    {
                        string pdir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logsWriteErr.txt");
                        File.AppendAllText(pdir, $"日誌輸出異常! msg:{e.Message}  st:{e.StackTrace}");
                        errCount++;
                    }
                }
            }
        }
    }
複製程式碼

二, 為Logs類建立一個列舉用於傳參, 方便使用

/// <summary>
    /// 日誌型別
    /// </summary>
    public enum LogType
    {
        Info = 0,
        Error = 1,
        Msg = 2,
        Post = 3,
        Verbose = 4,
        UrlError = 5,
        Api = 5
    }
複製程式碼

三, 接下來,就可以 引用Logs輸出日誌了,下面舉一個栗子送給你~

void process1()
        {
            int c = 0;
            while (isContinue)
            {
                // 輸出日誌
                Logs.WriteLog(LogType.Info, "run... " + (++c));
                Thread.Sleep(1200);
            }
        }
複製程式碼

寫日誌, 在程式維護中是必須的, 記錄執行過程, 能排查存在的問題.


相關文章