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

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

相关推荐
z落落1 小时前
C# Task WaitAll、WaitAny、WhenAll、WhenAny
开发语言·c#
玖玥拾3 小时前
C# 语言进阶(十四)Unity UI界面开发 + 网络消息联动
服务器·开发语言·网络·ui·unity·c#·游戏引擎
czhc11400756635 小时前
712:Atta. cursor;ToggleButton
c#
玖玥拾5 小时前
C# 语言进阶(十三)网络 DLL 库分层设计
服务器·开发语言·网络·网络协议·c#
雪靡6 小时前
WPF PerMonitorV2 下的跨窗口问题
c#·wpf
苍狼唤6 小时前
SQL+C# 增删改查(练习)
数据库·sql·c#
LibraJM19 小时前
一种适合程序员的 Agent 协作方式的实践
c#·copilot·agents
旋律翼21 天前
Qt Bridges for C# 深度技术解析
开发语言·qt·c#
吴可可1231 天前
判断多段线方向的鞋带公式法
c#