Wednesday, July 15, 2009

Log File


In this article, we will adopt a simple mechanism to log errors and exceptions in website,
The error will get logged in a text file on the server.
The error file will be created on a daily basis, whenever the error is encountered

Public Shared Sub WriteErrorLog(ByVal errorMessage As String, ByVal errorStack As String, ByVal methodName As String)
Dim path As String = "~/LOG/" & DateTime.Today.ToString("dd-MM-yy") & ".txt"
If (Not File.Exists(System.Web.HttpContext.Current.Server.MapPath(path))) Then
File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close()
End If
Using w As StreamWriter = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))
w.WriteLine(Constants.vbCrLf & "Log DateTime : " & DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantCulture))
w.WriteLine("Page :- " & System.Web.HttpContext.Current.Request.Url.AbsolutePath.ToString.Trim)
w.WriteLine("Function Name :- " & methodName)
w.WriteLine("Message :- " & errorMessage)
w.WriteLine("Stack Trace :- " & errorStack)
w.WriteLine("__________________________")
w.Flush()
w.Close()
End Using
End Sub
Protected Sub btnTest_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Try
Dim i As Integer = 1
Dim j As Integer = 0
Response.Write(i \ j)
Catch ex As Exception
WriteErrorLog(ex.Message, ex.StackTrace.ToString.Trim, ex.TargetSite.Name)
End Try
End Sub

OutPut
__________________________

Log DateTime : 07/15/2009 15:25:20
Page :- /Default.aspx
Function Name :- btnTest_Click
Message :- Attempted to divide by zero.
Stack Trace :- at Default.aspx.btnTest_Click(Object sender, EventArgs e) in D:\Test\Default.aspx.vb:line 107
__________________________


Same thing you can do in Globa.asax, at Application_Error event. You can get an Server last error by Server.GetLastError()

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
Dim objErr As Exception = Server.GetLastError().GetBaseException()

'Function Name not be correct at application level error
WriteErrorLog(objErr .Message, objErr .StackTrace.ToString.Trim, "")

'IF you want you can redirect to user after log into log file here
' Response.Redirect("Error.aspx")
End Sub

No comments:

Post a Comment