在ap.net Web项目中一直使用Elmah进行日志记录,

但一直有一个问题困扰我很久,那就是我如何自己生成一个错误并记录到Elmah里去。

你知道有时你需要在项目中生成一个错误用于一些特殊的需求

最开始之前我是这样处理的。

使用Sql语句自定义错误信息添加到Elmah的Sqlite数据库中,但这样做有一个问题,

如果Elmah更改存储方式非Sqlite(如Xml,txt,Mysql等)那么下面的方式就无效啦(错误信息无法在Elmah中显示)

     
public class CustomErrorSqlite{
static   string  UrlDecodeUtf( string  _val)
        {
             return   HttpUtility .UrlDecode(_val, System.Text. Encoding .UTF8);
        }
   static string StrDecode(string str)
        {
            return UrlDecodeUtf(str).Replace("&", "").Replace("<br />", "  ").Replace("<br>", "  ").Replace("<", "<").Replace(">", ">").Replace("\"", """).Replace("\'", "'").Replace(")", ")").Replace("(", "(").Replace("{", "{").Replace("}", "}").Replace("/", "/");
        }   
  static string GetServerVariables
        {
            get
            {
                StringBuilder sb = new StringBuilder("<serverVariables>");
                foreach (string str in HttpContext.Current.Request.ServerVariables)
                {
                    sb.Append(string.Format("<item name='{0}'><value string='{1}'/></item>", str, StrDecode(HttpContext.Current.Request.ServerVariables[str])));
                }
                sb.Append("</serverVariables>");
                return sb.ToString();
            }
        }
/// <summary>
        /// 错误信息,错误地址,错误详细信息
        /// AllXml列需要将@#等特殊字符进行处理,否则在查看Elmah详情时会出现
        /// </summary>
        /// <param name="message">错误信息</param>
        /// <param name="source">错误来源</param>
        /// <param name="detailmessage">详细的错误信息</param>
        public static void AddLog(string message, string source, string detailmessage)
        {
            detailmessage = StrDecode(UrlDecodeUtf(detailmessage));
            message = StrDecode(UrlDecodeUtf(message));
            source = StrDecode(UrlDecodeUtf(source));
 
            //使用Elmah的Sqlite数据库
            //如果在配置文件中更改sqlite数据库位置或更改为其他存储方式
            //下面的处理方式无效(数据无法在Elmah中显示和查看)
            string ConnectionString = string.Empty;
            foreach (ConnectionStringSettings str in ConfigurationManager.ConnectionStrings)
            {
                if (!str.Name.Contains("Elmah_SQLiteErrorLog"))
                    continue;
                ConnectionString = str.ConnectionString;
                break;
            }
            using (SQLiteConnection sQLiteConnection = new SQLiteConnection(ConnectionString))
            {
                using (SQLiteCommand sQLiteCommand = new SQLiteCommand("INSERT INTO Error (Application, Host, Type, Source, Message, User, StatusCode, TimeUtc, AllXml)VALUES (@Application, @Host, @Type, @Source, @Message, @User, @StatusCode, @TimeUtc, @AllXml);SELECT last_insert_rowid();", sQLiteConnection))
                {
                    SQLiteParameterCollection parameters = sQLiteCommand.Parameters;
                    parameters.Add("@Application", DbType.String, 60).Value = "/";
                    parameters.Add("@Host", DbType.String, 30).Value = Environment.UserName;
                    parameters.Add("@Type", DbType.String, 100).Value = "UserType";
                    parameters.Add("@Source", DbType.String, 60).Value = "UserType";
                    parameters.Add("@Message", DbType.String, 500).Value = message;
                    parameters.Add("@User", DbType.String, 50).Value = Environment.UserName;
                    parameters.Add("@StatusCode", DbType.Int64).Value = 300;
                    parameters.Add("@TimeUtc", DbType.DateTime).Value = DateTime.Now;
                    parameters.Add("@AllXml", DbType.String).Value = string.Format("<error   type=\"UserType\"  message=\"{0}\"  source=\"{1}\"  detail=\"\r\n{2}\r\nSource:{3}  \">{4}</error>", message, source, detailmessage + "\r\ndatetime:" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss:ms"), source, GetServerVariables);
 
                    try
                    {
                        sQLiteConnection.Open();
                        sQLiteCommand.ExecuteScalar();
                    }
                    catch (Exception)
                    {
 
                    }
                    finally
                    {
                        sQLiteCommand.Clone();
                    }
                }
            }
        }
    }
View Code

 

  自定义错误信息并写入到Elmah

经过搜索 发现一个更好的解决方案使用Elmah内部对象来添加错误信息,但可能性能上会有损耗,每次都会创建Error或Exception对象

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-06
  • 2021-05-29
  • 2021-08-07
  • 2021-11-10
猜你喜欢
  • 2022-12-23
  • 2021-06-17
  • 2022-12-23
  • 2021-05-25
  • 2021-05-27
相关资源
相似解决方案