如何在 ASP.NET 5/vNext/Core 中使用 Elmah?

2024-05-08

我对如何在 ASP.NET 5 / MVC 6 项目中使用 Elmah 有点困惑。我从 nuget 得到了包,它添加了"Elmah.Mvc": "2.1.2"到project.json 中的依赖项。

我不知道从这里到哪里去 - 以前,nuget 会向 web.config 添加条目,但现在已经消失了。我似乎无法在他们的 github 或其他地方找到任何示例。

我错过了一些简单的事情吗?


不使用 ELMAH,手动实现错误日志记录并不困难。此过程将捕获项目中发生的任何异常并将其记录到数据库表中。为此,请将以下内容添加到 Startup.cs 中的配置方法中

  if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
    app.UseBrowserLink();
  }
  else
  {
    app.UseExceptionHandler(builder =>
      {
        builder.Run(async context =>
        {
          context.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
          context.Response.ContentType = "text/html";

          var error = context.Features.Get<Microsoft.AspNetCore.Diagnostics.IExceptionHandlerFeature>();
          if (error != null)
          {
            LogException(error.Error, context);
            await context.Response.WriteAsync("<h2>An error has occured in the website.</h2>").ConfigureAwait(false);
          }
        });
      });
  }

也将其包含在 Startup.cs 中:

private void LogException(Exception error, HttpContext context)
{
  try
  {
    var connectionStr = Configuration["ConnectionString"];
    using (var connection = new System.Data.SqlClient.SqlConnection(connectionStr))
    {
      var command = connection.CreateCommand();
      command.CommandText = @"INSERT INTO ErrorLog (Application, Host, Type, Source, Path, Method, Message, StackTrace, [User],  WhenOccured)
    VALUES (@Application, @Host, @Type, @Source, @Path, @Method, @Message, @StackTrace, @User,  @WhenOccured)";
      connection.Open();

      if (error.InnerException != null)
        error = error.InnerException;

      command.Parameters.AddWithValue("@Application", this.GetType().Namespace);
      command.Parameters.AddWithValue("@Host", Environment.MachineName);
      command.Parameters.AddWithValue("@Type", error.GetType().FullName);
      command.Parameters.AddWithValue("@Source", error.Source);
      command.Parameters.AddWithValue("@Path", context.Request.Path.Value);
      command.Parameters.AddWithValue("@Method", context.Request.Method);
      command.Parameters.AddWithValue("@Message", error.Message);
      command.Parameters.AddWithValue("@StackTrace", error.StackTrace);
      var user = context.User.Identity?.Name;
      if (user == null)
        command.Parameters.AddWithValue("@User", DBNull.Value);
      else
        command.Parameters.AddWithValue("@User", user);
      command.Parameters.AddWithValue("@WhenOccured", DateTime.Now);

      command.ExecuteNonQuery();
    }
  }
  catch { }
}

请注意,您必须使用此函数中使用的结构在数据库中创建一个表。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 ASP.NET 5/vNext/Core 中使用 Elmah? 的相关文章

随机推荐