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();
        }

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

相关推荐
MM_MS36 分钟前
C# 线程与并发编程完全指南:从基础到高级带详细注释版(一篇读懂)
开发语言·机器学习·计算机视觉·c#·简单工厂模式·visual studio
公子小六3 小时前
推荐一种手动设置异步线程等待机制的解决方案
windows·microsoft·c#·.net
code bean4 小时前
【C++】全局函数和全局变量
开发语言·c++·c#
yi碗汤园4 小时前
C#实现对UI元素的拖拽
开发语言·ui·unity·c#
m***92384 小时前
【MySQL】C# 连接MySQL
数据库·mysql·c#
ironinfo6 小时前
C#性能优化随记
开发语言·性能优化·c#
czhc11400756638 小时前
Winform121 prograssbar Imagelist panel
c#
我是苏苏9 小时前
C#基础:如何创建一个类库并且封装成DLL
开发语言·c#
Yuyang_Leo9 小时前
eventTime+watermarker+allowedLateness到底窗口关闭时间是什么?
c#·linq