c#实现把异常写入日志实例(异常日志)
: :0 :2021-04-22 21:17:17
将异常写到日志文件中,可以在调试程序的时候知道程序发生过哪些异常,并且可以知道异常发生的位置。这点对需要进行长时间运行并调试的程序尤为有效。
///
/// 将异常打印到LOG文件
///
///异常
///日志文件地址
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 fs = new StreamWriter(LogAddress, true);
fs.WriteLine("当前时间:" + DateTime.Now.ToString());
fs.WriteLine("异常信息:" + ex.Message);
fs.WriteLine("异常对象:" + ex.Source);
fs.WriteLine("调用堆栈:n" + ex.StackTrace.Trim());
fs.WriteLine("触发方法:" + ex.TargetSite);
fs.WriteLine();
fs.Close();
}