Writing exceptions in log files (Logger class in VB.Net)

The follwing VB.NET sample code demonstrates how to write exceptions in a log file.


'
' This class is responsible for tracing application errors during runtime. It writes information to log file describing cause of error, file name & line number etc
'


Public Class Logger
Private Shared Sub Info(ByVal info As Object)

'Gets folder & file information of the log file
Dim folderName As String = ConfigurationManager.AppSettings("").ToString()
Dim fileName As String = ConfigurationManager.AppSettings("").ToString()
Dim dir As DirectoryInfo = New DirectoryInfo(folderName)

'Check for existence of logger file
If File.Exists(fileName) Then
Try
Dim fs As FileStream = New FileStream(fileName, FileMode.Append, FileAccess.Write)
Dim sw As StreamWriter = New StreamWriter(fs)
sw.WriteLine(DateTime.Now + " " + info.ToString)
sw.Close()
fs.Close()
Catch dirEx As DirectoryNotFoundException
LogInfo(dirEx)
Catch ex As FileNotFoundException
LogInfo(ex)
Catch Ex As Exception
LogInfo(Ex)
End Try
Else
'If file doesn't exist create one
Try
dir = Directory.CreateDirectory(dir.FullName)
Dim fileStream As FileStream = File.Create(fileName)
Dim sw As StreamWriter = New StreamWriter(fileStream)
sw.WriteLine(DateTime.Now + info.ToString)
sw.Close()
fileStream.Close()
Catch fileEx As FileNotFoundException
LogInfo(fileEx)
Catch dirEx As DirectoryNotFoundException
LogInfo(dirEx)
Catch ex As Exception
LogInfo(ex)
End Try
End If
End Sub
Public Shared Sub LogInfo(ByVal ex As Exception)
Try

'Writes error information to the log file including name of the file, line number & error message description
Dim trace As Diagnostics.StackTrace = New Diagnostics.StackTrace(ex, True)
Dim fileNames As String = trace.GetFrame((trace.FrameCount - 1)).GetFileName()
Dim lineNumber As Int32 = trace.GetFrame((trace.FrameCount - 1)).GetFileLineNumber()

Info("Error In" + fileNames + "Line Number" + lineNumber.ToString() + "Error Message" + ex.Message)
Catch genEx As Exception
Info(ex.Message)
End Try

End Sub

Public Shared Sub LogInfo(ByVal message As String)
Try

'Write general message to the log file
Info("Message" + message)
Catch genEx As Exception
Info(genEx.Message)
End Try

End Sub
End Class


Comments

Author: thazinmon10 Jun 2009 Member Level: Bronze   Points : 1

I would like to know that what should I import for configurationManager. Please kindly reply me.

Guest Author: mary jones30 May 2012

Nice Post it helpful for my project.
Accessible in whole project and return required useful data.

Keep it up!

Guest Author: ian30 Jul 2013

where do I call this class from?



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: