In many applications we
may came across lot logging techniques. Like writing log files in text file,
some custom log file, log in event viewer, logging information in Databases
etc.,
Here we are going to see
a simple code in VB.net programming language that will help in logging
information for any applications.
1. Use a system.IO namespace for any file
handling operations.
2. When a variable is considered as a
shared object, it means there is no need for object creation in the
instantiation class.
3. The
System.Windows.Forms.Application.StartupPath
is a application running folder
path
4. Check to see the log folder and log
file already exists. If not exist then create one or else concatenate with the existing
content in the log file.
5. Create a filestream object and using streamwriter write the content to the log file.
Imports System
Imports System.IO
Public Class Log
Private Shared LogPath As String =
System.Windows.Forms.Application.StartupPath + "\Log\"
Private Shared fs As FileStream
Private Shared sw As StreamWriter
''' <summary>
''' Log result
in the log file
''' </summary>
''' <remarks></remarks>
Public Shared Sub Log(ByVal logStr As String)
Dim logDir As DirectoryInfo
Dim logFileName As String = LogPath + "Log.txt"
logDir = New DirectoryInfo(LogPath)
If (Not logDir.Exists) Then logDir.Create()
If (Not File.Exists(logFileName)) Then File.Create(logFileName)
If File.Exists(logFileName) Then
sw = File.AppendText(logFileName)
sw.WriteLine(logStr.ToString())
sw.Close()
Else
fs = New FileStream(logFileName, FileMode.OpenOrCreate,
FileAccess.ReadWrite, FileShare.ReadWrite)
sw = New StreamWriter(fs)
sw.WriteLine()
sw.WriteLine(logStr.ToString())
sw.Close()
End If
End Sub
End Class
No comments:
Post a Comment