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

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

相关推荐
水煮庄周鱼鱼36 分钟前
C# 入门简介
开发语言·c#
软件黑马王子1 小时前
Unity游戏制作中的C#基础(6)方法和类的知识点深度剖析
开发语言·游戏·unity·c#
Nicole Potter2 小时前
请说明C#中的List是如何扩容的?
开发语言·面试·c#
gu204 小时前
c#编程:学习Linq,重几个简单示例开始
开发语言·学习·c#·linq
pchmi8 小时前
CNN常用卷积核
深度学习·神经网络·机器学习·cnn·c#
yuanpan8 小时前
23种设计模式之《组合模式(Composite)》在c#中的应用及理解
开发语言·设计模式·c#·组合模式
滴_咕噜咕噜9 小时前
C#基础总结:常用的数据结构
开发语言·数据结构·c#
万兴丶13 小时前
Unity 适用于单机游戏的红点系统(前缀树 | 数据结构 | 设计模式 | 算法 | 含源码)
数据结构·unity·设计模式·c#
程序猿多布14 小时前
C#设计模式 学习笔记
设计模式·c#
软件黑马王子20 小时前
Unity游戏制作中的C#基础(5)条件语句和循环语句知识点全解析
游戏·unity·c#