Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Page errors to app log file

Here's the simple code that I wrote not long ago to catch exception on page level and write them down in applications log file into applications root directory:

 Protected Sub Page_Error(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Error

Dim err As Exception = Server.GetLastError()

Dim write As String

    write = err.Message

Dim fileExists As Boolean

    fileExists = My.Computer.FileSystem.FileExists("C:\Inetpub\wwwroot\test\error.log")

If fileExists = False Then

   My.Computer.FileSystem.WriteAllText("C:\Inetpub\wwwroot\test\error.log", String.Empty, False)

   My.Computer.FileSystem.WriteAllText("C:\Inetpub\wwwroot\test\error.log", _

   "/***************** " & DateTime.Now() & " *****************/" & vbCrLf & vbCrLf & _

   "Type: Page Level Error" & vbCrLf & _

   "Client IP: " & Request.ServerVariables("Remote_Addr") & vbCrLf & _

   "Page: " & Request.UrlReferrer.AbsoluteUri & vbCrLf & _

   "Error: " & write & vbCrLf & vbCrLf & _

   "----------------------------------------------------------" & vbCrLf & vbCrLf, True)

Else

   My.Computer.FileSystem.WriteAllText("C:\Inetpub\wwwroot\test\error.log", _

   "/***************** " & DateTime.Now() & " *****************/" & vbCrLf & vbCrLf & _

   "Type: Page Level Error" & vbCrLf & _

   "Client IP: " & Request.ServerVariables("Remote_Addr") & vbCrLf & _

   "Page: " & Request.UrlReferrer.AbsoluteUri & vbCrLf & _

   "Error: " & write & vbCrLf & vbCrLf & _

   "----------------------------------------------------------" & vbCrLf & vbCrLf, True)

End If

Server.ClearError()

Response.Redirect(Request.UrlReferrer.AbsoluteUri)

End Sub

2 Comments

  • >Response.Redirect(Request.UrlReferrer.AbsoluteUri)
    Redirecting the user back to the page where the exception occurred could, in some cases, lead to an infinite loop. In addition, Request.UrlReferrer could be null with some users who have decided to turn off the option in their browsers.

    MS allows you add health monitoring to your app including writing to a local file: http://weblogs.asp.net/rajbk/archive/2006/02/09/437846.aspx

    Raj

  • 14cqS7 I appreciate you sharing this article.Really looking forward to read more. Great.

Comments have been disabled for this content.