zoukankan      html  css  js  c++  java
  • C# 程序出现错误或异常,将异常信息写入指定日志文件

    C#程序当出现异常时,往往是在页面上出现异常提示的,我们可以将程序中所有出现的异常信息写入到指定的错误日志文件里,这样当网站程序出错时,我们可以直接通过查看错误日志,来分析所有的异常。方便,快捷

    using System;
    using System.IO;
    
    	/// <summary>
    	/// log 的摘要说明。
    	/// </summary>
    	public class NetLog
    	{
    		public NetLog()
    		{
    			//
    			// TODO: 在此处添加构造函数逻辑
    			//
    		}
    		//添加文本
            public void WriterLog(string path, string logName, string log)
            {
                string page = "";
                WriterLog(path, logName, log, page);
            }
    
              //参数path:日志文件路径(不包括文件名)
              //参数logName:日志文件名
              //参数log:异常信息
              //参数page:发生异常页面
    		public void WriterLog(string path, string logName, string log,string page)
    		{
    			System.DateTime tm = DateTime.Now;
    			string p = path + logName;
    			if (!Directory.Exists(path))//判断路径下目录是否存在
    			{
    				Directory.CreateDirectory(path);
    				if (!File.Exists(p))
    				{
    					using (StreamWriter sw = File.CreateText(p))
    					{
    						sw.WriteLine(log + "----------" + tm + "[" + page + "]");
    					}
    
    				}
    				else
    				{
    					using (StreamWriter sw = File.AppendText(p))
    					{
                            sw.WriteLine(log + "----------" + tm + "[" + page + "]");
    					}
    				}
    			}
    			else
    			{
    				if (!File.Exists(p))
    				{
    					using (StreamWriter sw = File.CreateText(p))
    					{
                            sw.WriteLine(log + "----------" + tm + "[" + page + "]");
    					}
    
    				}
    				else
    				{
    					using (StreamWriter sw = File.AppendText(p))
    					{
                            sw.WriteLine(log + "----------" + tm + "[" + page + "]");
    					}
    				}
    
    			}
    		}
    	}
    
    
    

    这样,有了上面这个写错误日志的类,那么我们就可以在底层与数据库交涉的代码中通过调用WriteLod(,,,,)方法来写错误日志

    try
    {
         ...   //正常的操作数据库代码
    }
    catch(Exception ex)
    {
            WriteLog("日志文件路径","日志文件名",ex.Exception,"发生错误页面名称");
    }
    
  • 相关阅读:
    2021hdu多校第二场补题
    ORACLE数据库之SQL语言基础
    EXCEL应用
    element-ui闭坑
    题解 CF1559E 【Mocha and Stars】
    题解 CF1530D 【Secret Santa】
    题解 CF1209E2 【Rotate Columns (hard version)】
    题解 CF761E 【Dasha and Puzzle】
    题解 UVA437 【巴比伦塔 The Tower of Babylon】
    题解 P6100 【[USACO19FEB]Painting the Barn G】
  • 原文地址:https://www.cnblogs.com/jkyweb/p/1837031.html
Copyright © 2011-2022 走看看