C#按照日期輸出程式日誌

Tiger_shl發表於2018-11-27
namespace LogData
{
    public class Log
    {
        private static LogManager logManager;
        static Log()
        {
            logManager = new LogManager();
        }

        public static void WriteLog(LogFile logFile, string msg)
        {
            try
            {
                logManager.WriteLog(logFile, msg);
            }
            catch
            {
            }
        }

        public static void WriteLog(string msg)
        {
            try
            {
                logManager.WriteLog(LogFile.Info, msg);
            }
            catch
            {
            }
        }

        public static void WriteLog(string logFile, string msg)
        {
            try
            {
                logManager.WriteLog(logFile, msg);
            }
            catch
            {

            }
        }
    }

    public class LogManager
    {
        private string logFileName = string.Empty;
        private string logPath = "Log";
        private string logFileExtName = "log";
        private bool writeLogTime = true;
        private bool logFileNameEndWithDate = true;
        private Encoding logFileEncoding = Encoding.UTF8;
        private object obj = new object();


        #region 建構函式
        public LogManager()
        {
            this.LogPath = "Log";
            this.LogFileExtName = "log";
            this.WriteLogTime = true;
            this.logFileNameEndWithDate = true;
            this.logFileEncoding = Encoding.UTF8;
        }
        public LogManager(string logPath, string logFileExtName, bool writeLogTime)
        {
            this.LogPath = logPath;
            this.LogFileExtName = logFileExtName;
            this.WriteLogTime = writeLogTime;
            this.logFileNameEndWithDate = true;
            this.logFileEncoding = Encoding.UTF8;
        }

        #endregion

        #region 屬性
        /// <summary>
        /// Log 檔案路徑
        /// </summary>
        public string LogPath
        {
            get
            {
                if (this.logPath == null || this.logPath == string.Empty)
                {
                    //Application.StartupPath
                    this.logPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, DateTime.Now.ToString("yyyy-MM-dd"));
                }
                return this.logPath;
            }
            set
            {
                this.logPath = value;
                if (this.logPath == null || this.logPath == string.Empty)
                {
                    //Application.StartupPath
                    this.logPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, DateTime.Now.ToString("yyyy-MM-dd"));
                }
                else
                {
                    try
                    {
                        // 判斷是否不是絕對路徑(絕對路徑裡還有":")
                        if (this.logPath.IndexOf(Path.VolumeSeparatorChar) >= 0)
                        { /* 絕對路徑 */}
                        else
                        {
                            // 相對路徑
                            this.logPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory + this.logPath, DateTime.Now.ToString("yyyy-MM-dd"));
                        }
                        if (!Directory.Exists(this.logPath))
                            Directory.CreateDirectory(this.logPath);
                    }
                    catch
                    {
                        this.logPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, DateTime.Now.ToString("yyyy-MM-dd"));
                    }
                    if (!this.logPath.EndsWith(@"\"))
                        this.logPath += @"\";
                }
            }
        }

        /// <summary>
        /// Log 副檔名
        /// </summary>
        public string LogFileExtName
        {
            get { return this.logFileExtName; }
            set { this.logFileExtName = value; }
        }

        /// <summary>
        /// 是否在每個Log行前面新增當前時間
        /// </summary>
        public bool WriteLogTime
        {
            get { return this.writeLogTime; }
            set { this.writeLogTime = value; }
        }

        /// <summary>
        /// 日誌檔名是否帶日期
        /// </summary>
        public bool LogFileNameEndWithDate
        {
            get { return logFileNameEndWithDate; }
            set { logFileNameEndWithDate = value; }
        }

        /// <summary>
        /// 日誌檔案的字元編碼
        /// </summary>
        public Encoding LogFileEncoding
        {
            get { return logFileEncoding; }
            set { logFileEncoding = value; }
        }
        #endregion

        #region 公有方法
        public void WriteLog(string logFile, string msg)
        {
            lock (obj)
            {
                try
                {
                    string dateString = string.Empty;
                    if (this.logFileNameEndWithDate || logFile.Length == 0)
                    {
                        dateString = DateTime.Now.ToString("yyyyMMdd");
                    }

                    logFileName = string.Format("{0}{1}{2}.{3}",
                                                this.LogPath,
                                                logFile,
                                                dateString,
                                                this.logFileExtName);
                    using (StreamWriter sw = new StreamWriter(logFileName, true, logFileEncoding))
                    {
                        if (writeLogTime)
                        {
                            sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss: ") + msg);
                        }
                        else
                        {
                            sw.WriteLine(msg);
                        }
                    }
                }
                catch
                {

                }
            }
        }

        public void WriteLog(LogFile logFile, string msg)
        {
            this.WriteLog(logFile.ToString(), msg);
        }

        public void WriteLog(string msg)
        {
            this.WriteLog(string.Empty, msg);
        }

        #endregion
    }

    public enum LogFile
    {
        Trace,
        Error,
        SQL,
        SQLError,
        Login,
        Info,
        WeChat
    }
}

使用時直接呼叫公用方法WriteLog,裡面設定了錯誤型別.

每天的日誌檔案輸出成一個資料夾,方便查閱

轉自:C#中的一種按日期分資料夾的日誌寫法

相關文章