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); } } }
作者:唐宋元明清2188
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。