C# 记录错误日志

程序的错误日志如何记录下来?

可以在遇到异常时,Catch异常,然后把异常的信息输出到txt文件中即可

    /// <summary>
    /// 错误日志
    /// </summary>
    public class LogHelper
    {
        private static object lockFlag = new object();
        private static string LOG_FILE_PATH = AppDomain.CurrentDomain.BaseDirectory + "Log";
        /// <summary>
        /// 记录日志
        /// 异常
        /// </summary>
        /// <param name="ex"></param>
        public static void LogError(Exception ex)
        {
            LogInfo(String.Format("ExType:{0}\r\nExMessage:{1}\r\nExSource:{2}\r\nExStack:\r\n{3}\r\n",
                ex.GetType(), ex.Message, ex.Source, ex.StackTrace));
        }
        public static void LogInfo(string msg)
        {
            lock (lockFlag)
            {
                IOHelper.CreateDirectory(LOG_FILE_PATH);
                string fileName = LOG_FILE_PATH + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                msg = String.Format("------------------------{0}------------------------------\r\n", DateTime.Now) + msg;
                msg += "\r\n\r\n\r\n";
                File.AppendAllText(fileName, msg);
            }
        }
    }

 

posted @ 2016-08-28 22:04  唐宋元明清2188  阅读(2762)  评论(0编辑  收藏  举报