8

I am a bit confused about how to use Elmah in the ASP.NET 5 / MVC 6 projects. I got the package from nuget and it added "Elmah.Mvc": "2.1.2" to dependencies in project.json.

I am not sure where to go from here - back in the day, nuget would add entries to the web.config which is now gone. And I can't seem to find any examples on their github or elsewhere.

Am I missing something simple?

AngryHacker
  • 59,598
  • 102
  • 325
  • 594
  • Not all packages have been updated to be compatible with ASP.NET Core. Given the level of integration needed between Elmah and the ASP.NET stack, I would say Elmah hasn't been updated yet. – mason Jan 29 '16 at 19:54
  • Possible duplicate of [ELMAH on ASP.NET vNext?](http://stackoverflow.com/questions/28907017/elmah-on-asp-net-vnext) – blowdart Jan 30 '16 at 14:28
  • 1
    Check out https://github.com/ElmahCore/ElmahCore – Rosdi Kasim Jan 21 '19 at 15:48

2 Answers2

15

Instead of using ELMAH, it's not hard to implement error logging manually. This process will catch any exception that occurs in the project and log it to a database table. To do this, add the following to the Configure method in 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);
          }
        });
      });
  }

Include this in Startup.cs as well:

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 { }
}

Note that you will have to create a table in your database with the structure used in this function.

Rono
  • 3,171
  • 2
  • 33
  • 58
  • Hmm, doesn't seem to fire when I throw a new exception... Am I not understanding how this is suppose to work? – Warren LaFrance Dec 19 '17 at 18:24
  • Just guessing, but is it because you are trying this in development mode? If that's the case, it will display error details on the webpage instead of calling LogException. That can be changed with the if statement in the first code block. – Rono Dec 19 '17 at 18:54
3

ELMAH hasn't been updated to support ASP.NET Core yet. Atif Aziz did some work building a web.config free configuration module called Bootstrapper. Bootstrapper doesn't support ASP.NET Core (as of my knowledge). But I'm pretty sure that work supporting the new version will start as soon as we get nearer to RTM.

ThomasArdal
  • 4,999
  • 4
  • 33
  • 73
  • If you ask me, it's daft to go an name a module `Bootstrapper`, given that is how the familiar JS and CSS library is known. – ProfK May 17 '17 at 11:53