Friday, July 25, 2008

Text File Logger in VB.NET

I use Log4Net and Trace at work. But sometimes I use a simple logger to log any error in an quick solution. The best feature about this logger is that:

  • It is simple to use & understand
  • The log file is generated based on date and it shows the timestamp of the logging message.

Imports System.IO

Imports System.Reflection


Public Class Logger


Public Shared Sub log(ByVal message As String)

Dim strAssemblyPath As String = IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)

Dim logPath As String = Path.Combine(strAssemblyPath, "Log")

If Not Directory.Exists(logPath) Then

Directory.CreateDirectory(logPath)

End If

Dim logFilePath As String = Path.Combine(logPath, _

String.Format("Log_{0}_{1}_{2}.log", DateTime.Now.Year.ToString, DateTime.Now.Month.ToString, DateTime.Now.Day.ToString))

Using sw As New StreamWriter(logFilePath, True)

sw.Write("[" + DateTime.Now + "] ")

sw.WriteLine(message)

sw.Close()

End Using

End Sub


End Class



It is a coincidence that I run a search on Google which return me a very similar logging mechanism provided by Chris. His log class also caters for writing entries to event log. If you want to write entries to the event log, you need to watch out for the max size of the event log. You can check out his blog here.

blog comments powered by Disqus