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

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

相关推荐
宝桥南山9 小时前
GitHub Models - 尝试一下使用GitHub Models
microsoft·ai·微软·c#·github·.netcore
hixiong12312 小时前
C# OpenvinoSharp部署INSID3
开发语言·人工智能·ai·c#·openvinosharp
星辰徐哥12 小时前
Unity C#入门:变量的定义与访问权限(public/private)
unity·c#·lucene
leoufung13 小时前
LeetCode 30:Substring with Concatenation of All Words 题解(含 C 语言 uthash 实现)
c语言·leetcode·c#
hacker70713 小时前
Visual Studio安装教程(C#开发版)
ide·c#·visual studio
SKY -dada13 小时前
Understand 使用教程
开发语言·c#·流程图·软件构建·敏捷流程·代码复审·源代码管理
William_cl16 小时前
【C#/.NET 进阶】ASP.NET 架构与最佳实践:DI 依赖注入(IoC 核心)从入门到避坑
c#·asp.net·.net
武藤一雄16 小时前
WPF:MessageBox系统消息框
前端·microsoft·c#·.net·wpf
武藤一雄16 小时前
WPF进阶:万字详解WPF如何性能优化
windows·性能优化·c#·.net·wpf·.netcore·鲁棒性
xiaogutou11211 天前
2026年历史课件PPT模板选购指南:教师备课效率与精度的平衡方案
开发语言·c#