日志记录帮助类
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Common { public class Log { public static string logAddress = ConfigurationManager.AppSettings["LogAddress"] + "Log"; /// <summary> /// 将异常打印到LOG文件 /// </summary> /// <param name="ex">异常</param> /// <param name="LogAddress">日志文件地址</param> public static void WriteLog(Exception ex, string LogAddress = "") { if (!Directory.Exists(logAddress)) { Directory.CreateDirectory(logAddress); } //如果日志文件为空,则默认在Debug目录下新建 YYYY-mm-dd_Log.log文件 if (LogAddress == "") { LogAddress = logAddress + '\\' + 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("调用堆栈:\n" + ex.StackTrace.Trim()); sw.WriteLine("触发方法:" + ex.TargetSite); sw.WriteLine(); sw.Close(); } } }