.netloggingerror-handlingwebformselmah

How to turn off automatic Elmah logging?


I'd like to disable automatic exception logging in Elmah, while leaving manual logging enabled, e.g.

ErrorSignal.FromCurrentContext.Raise(ex)

My situation is nearly identical to this one, with the sole difference being that I'm using XML logging instead of SQL. I'm also generating a unique ID for the exception that I'm using for tracking purposes.

When I disable the ErrorLog module in Web.config, however, as suggested in the answer, I also lose the ability to manually log the exception. Nothing gets logged at that point.

Here's the code from Global.asax:

Sub Application_Error(Sender As Object, e As EventArgs)
  Dim sCode As String

  sCode = Utils.NewId(IdModes.AlphaNumeric)

  Try
    Throw New LinkedException(sCode, Me.Server.GetLastError)

  Catch ex As LinkedException
    ErrorSignal.FromCurrentContext.Raise(ex)

  Finally
    Me.Server.ClearError()

  End Try

  Me.Context.Redirect($"~/oops/{sCode}")
End Sub

...and here's LinkedException:

Imports System.Web

Public Class LinkedException
  Inherits HttpException

  Public Sub New(ExceptionCode As String, ex As HttpException)
    MyBase.New(ex.ErrorCode, $"[{ExceptionCode}] {ex.Message}", ex)
  End Sub
End Class

Is it possible to turn off automatic logging but leave manual turned on? When I turn on automatic I get two entries, when I turn it off I get none.


Solution

  • As it turns out, it's best to let ELMAH do the heavy lifting and not use Application_Error at all.

    Imports Elmah
    
    Public Class Global_asax
      Inherits HttpApplication
    
      Private Sub ErrorLog_Filtering(Sender As Object, e As ExceptionFilterEventArgs)
        Dim oContext As HttpContext
        Dim oError As [Error]
        Dim sCode As String
    
        oContext = TryCast(e.Context, HttpContext)
        sCode = Utils.NewId(IdModes.AlphaNumeric)
    
        If oContext.IsNotNothing Then
          ' Create a customized error containing the error code
          oError = New [Error](e.Exception, oContext) With {.User = $"[{sCode}] { .User}"}
    
          ' Log the customized error
          ErrorLog.GetDefault(oContext).Log(oError)
    
          ' Dismiss the incoming exception so
          ' we don't get a duplicate entry
          e.Dismiss()
        End If
    
        Me.Response.Redirect($"~/oops/{sCode}", True)
      End Sub
    End Class