C#添加錯誤日誌信息

廢話很少說,直接上代碼,關鍵代碼都有註釋,不理解的能夠留言提出.spa

   private static StreamWriter streamWriter; //寫文件  
        //將錯誤信息寫入文件中
        public static void WriteError(string message)
        {
            try
            {
                //DateTime dt = new DateTime();
                string directPath = ConfigurationManager.AppSettings["LogFilePath"].ToString().Trim();    //在得到文件夾路徑
                if (!Directory.Exists(directPath))   //判斷文件夾是否存在,若是不存在則建立
                {
                    Directory.CreateDirectory(directPath);
                }
                directPath += string.Format(@"\{0}.log", DateTime.Now.ToString("yyyy-MM-dd"));
                if (streamWriter == null)
                {
                    streamWriter = !File.Exists(directPath) ? File.CreateText(directPath) : File.AppendText(directPath);    //判斷文件是否存在若是不存在則建立,若是存在則添加。
                }
                streamWriter.WriteLine("***********************************************************************");
                streamWriter.WriteLine(DateTime.Now.ToString("HH:mm:ss"));
                streamWriter.WriteLine("輸出信息:錯誤信息");
                if (message != null)
                {
                    streamWriter.WriteLine("異常信息:\r\n" + message);
                }
            }
            finally
            {
                if (streamWriter != null)
                {
                    streamWriter.Flush();
                    streamWriter.Dispose();
                    streamWriter = null;
                }
            }
        }

ok,今天的分享就到這裏了,有疑問的歡迎留言!code

相關文章
相關標籤/搜索