代码比较简单,仅提供一种思路
/// <summary> /// 将异常打印到LOG文件 /// </summary> /// <param name="ex">异常</param> /// <param name="LogAddress">日志文件地址</param> public static void WriteLog(Exception ex, string LogAddress = "") { //如果日志文件为空,则默认在Debug目录下新建 YYYY-mm-dd_Log.log文件 if (LogAddress == "") { LogAddress = Environment.CurrentDirectory + '\' + DateTime.Now.Year + '-' + DateTime.Now.Month + '-' + DateTime.Now.Day + "_Log.log"; } //把异常信息输出到文件 StreamWriter sw = new StreamWriter(LogAddress, true); sw.WriteLine("当前时间:" + DateTime.Now.ToString()); sw.WriteLine("异常信息:" + ex.Message); sw.WriteLine("异常对象:" + ex.Source); sw.WriteLine("调用堆栈: " + ex.StackTrace.Trim()); sw.WriteLine("触发方法:" + ex.TargetSite); sw.WriteLine(); sw.Close(); }