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

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

相关推荐
程序设计实验室10 小时前
C# 扩展方法只会写 this 吗?C# 14 新语法直接把扩展方法玩出了花
c#
唐青枫12 小时前
C#.NET SignalR 深入解析:实时通信、Hub 与连接管理实战
c#·.net
唐宋元明清218818 小时前
.NET Win32磁盘动态卷/跨区卷触发“函数不正确”问题排查
windows·c#·存储
hez201019 小时前
Satori GC:同时做到高吞吐、低延时和低内存占用
c#·.net·.net core·gc·clr
唐青枫2 天前
C#.NET Channel 深入解析:高性能异步生产者消费者模型实战
c#·.net
小峥降临2 天前
Rokid UXR 的手势追踪虚拟中更真实的手实战开发【含 工程源码 和 最终完成APK】
c#
晨星shine6 天前
GC、Dispose、Unmanaged Resource 和 Managed Resource
后端·c#
用户298698530146 天前
.NET 文档自动化:Spire.Doc 设置奇偶页页眉/页脚的最佳实践
后端·c#·.net
用户3667462526746 天前
接口文档汇总 - 2.设备状态管理
c#
用户3667462526746 天前
接口文档汇总 - 3.PLC通信管理
c#