c#堆栈跟踪;c#异常原因查找打印;c#打印错误日志

#region 创建错误日志
        /// <summary>
        /// 创建错误日志
        /// </summary>
        public void createLog(Exception e)
        {
            //创建堆栈跟踪器
            StackTrace ss = new StackTrace(true);

            //异常字符串
            string systemModule = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + Environment.NewLine;
            //拼接异常信息
            systemModule += "异常SQL语句:" + SQLSTRING + Environment.NewLine;

            //所有堆栈帧的副本
            StackFrame[] sfs = ss.GetFrames();
            //循环堆栈帧的副本
            for (int i = 1; i < sfs.Length; i++)
            {
                //错误方法名(index:0为本身的方法;1为调用方法;2为其上上层,依次类推)
                MethodBase mb = ss.GetFrame(i).GetMethod();

                //错误行号
                string num = ss.GetFrame(i).GetFileLineNumber().ToString();

                //拼接异常信息
                systemModule += "模块名:" + mb.Module.ToString() + Environment.NewLine;
                systemModule += "命名空间名:" + mb.DeclaringType.Namespace + Environment.NewLine;
                systemModule += "类名:" + mb.DeclaringType.Name + Environment.NewLine;
                systemModule += "方法名:" + mb.Name + Environment.NewLine;
                systemModule += "错误行号:" + num + Environment.NewLine;
                systemModule += "异常原因:" + e.Message + Environment.NewLine;

            }
            //拼接异常信息
            systemModule += Environment.NewLine + Environment.NewLine;


            //日志文件夹路径
            String directory = System.AppDomain.CurrentDomain.BaseDirectory;
            String logPath = directory + "log";
            //判断日志文件夹是否存在
            if (!Directory.Exists(logPath))
            {
                //不存在创建
                Directory.CreateDirectory(logPath);
            }
            //日志文件(每天创建不同的日志文件)
            String logFilePath = logPath + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
            //判断日志文件是否存在
            if (!File.Exists(logFilePath))
            {
                //不存在创建日志文件
                FileStream createFS = new FileStream(logFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                createFS.Close();
            }
            //创建FileStream(在日志文件后面追加写入新日志)
            FileStream fs = new FileStream(logFilePath, FileMode.Append);
            // 创建写入流
            StreamWriter sw = new StreamWriter(fs);
            // 写入异常信息
            sw.WriteLine(systemModule);
            //关闭文件
            sw.Close();
        }
        #endregion

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值