Wednesday, March 25, 2009

Error Logging Windows Application VB.NET

Logging is very important for debugging exception at run time; normally logging will help us finding out problem in live environment.

I am post here a logging function using VB.NET, Just add this function in you class and create a directory in C: called Logs.

Public Sub Log(ByVal message As String)
             ' Check whether log.txt is already present or not
               If Not File.Exists("C:\Logs\log.txt") Then
                         'Create if not present
                       Dim fs As FileStream = New FileStream("C:\Logs\log.txt",   FileMode.OpenOrCreate, FileAccess.ReadWrite)
                      Dim s As StreamWriter = New StreamWriter(fs)
                           s.Close()
                            s.Dispose()
fs.Close()
fs.Dispose()
End If
'Open log.txt in append mode to log errors
Dim fs1 As FileStream = New FileStream("C:\Logs\log.txt", FileMode.Append, FileAccess.Write)
Dim s1 As StreamWriter = New StreamWriter(fs1)
'Wrting a line with error message
s1.Write("Message: " & message & vbCrLf)
'Logging the Date and Time of error
s1.Write("Date/Time: " & DateTime.Now.ToString() & vbCrLf)
s1.Close()
s1.Dispose()
fs1.Close()
fs1.Dispose()
End Sub


Now testing the above function

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
Dim j As Integer = 10
Dim i As Integer = 0
Dim k As Integer = j / i
Catch ex As Exception
Log(ex.Message)
End Try
End Sub


Hope this helps

1 comment:

  1. This is a good logger:
    http://www.kellermansoftware.com/p-14-net-logging-library.aspx

    ReplyDelete