c#输出错误日志到指定文件夹

把输出错误写成一个方法,当出现错误的时候调用方法,把时间和出错的方法名用作文件名,输出在本地某个位置

csharp 复制代码
  //错误输出
        public string WriteERR(string PageName, string ERR)
        {
            // 获取当前时间
            DateTime currentTime = DateTime.Now;
            string formattedTime = currentTime.ToString("yyyyMMddHHmm") + "_";
            //获取配置文件里面配置的错误输出地址
            string filePath = ConfigurationManager.AppSettings["ErrPathLog"].ToString() + "\\" + formattedTime + PageName + ".txt";
            try{
                // 确保目录存在
                string directoryPath = Path.GetDirectoryName(filePath);
                if (!Directory.Exists(directoryPath)) {
                    Directory.CreateDirectory(directoryPath);
                }
                // 使用 StreamWriter 创建和写入文件
                using (StreamWriter writer = new StreamWriter(filePath)){
                    writer.Write(ERR);
                }
                return null;
            }
            catch (Exception E){
                string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                WriteERR(methodName, E.ToString());
                return("ERR" + E.Message);
            }
        }

方法代码调用

csharp 复制代码
public ActionResult OSLL_index(){
            try
            {
                
            catch (Exception E)
            {
            //获取到方法名称作为文件名输出
                string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                WriteERR(methodName, E.ToString());
                return Json("ERR" + E.Message);
            }
            return View();
        }

当软件部署后。即可在出错时输出错误信息

相关推荐
yue0081 小时前
C# Environment类的介绍
开发语言·c#·environment
c#上位机2 小时前
halcon图像去噪—高斯滤波
c#·上位机·halcon·机器视觉
神奇的板烧3 小时前
Java泛型不变性引发的类型转换问题及解决方案
java·c#
Aevget4 小时前
界面控件开发包DevExpress v25.1.7更新上线——修复一些小bug
c#·wpf·winform·devexpress·ui开发·用户界面
Q180809515 小时前
手撕BP与CNN:不依赖外源库,探寻神经网络原理
c#
c#上位机6 小时前
halcon图像分割之动态阈值分割
图像处理·人工智能·计算机视觉·c#·halcon
崇文殿大学士6 小时前
C# MediatR 中介者模式 观察者模式
观察者模式·c#·中介者模式
derive_magic7 小时前
wwwwwwjava
开发语言·c#
代数狂人7 小时前
【秒懂C#14 第一章:C#简介】
开发语言·c#
web3.08889997 小时前
淘宝客API调用折扣商品搜索及商品详情示例代码
开发语言·c#