I was also in search of such vb.net code to create a log file and after lots of google , I got a vb.net code and did some modification to match my requirement and after modification my code is working fine. This code is just a class.
Imports System.IO
Public Class Classlogger
Private Shared Sub Info(ByVal info As Object)
'Gets folder
& file information of the log file
Dim
filename As String
= "C:\Program Files\abc\log.rtf"
' Dim sw As
StreamWriter
Dim
portfolioPath As String
= My.Application.Info.DirectoryPath
'Dim s As
StreamWriter
'Dim
portfolioPath As String = My.Application.Info.DirectoryPath
'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(vbCrLf & "--- " + vbCrLf + 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("C:\Program Files\IRBn WMS")
Dim
fileStream As FileStream =
File.Create(filename)
Dim
sw As StreamWriter = New
StreamWriter(fileStream)
sw.WriteLine(vbCrLf & "--- " + vbCrLf + 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(vbCrLf + "Error In: " + fileNames + vbCrLf + "Line Number:" + lineNumber.ToString() +
vbCrLf + "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
and I called in a event
Private Sub BtnCancel_Click(ByVal
sender As System.Object, ByVal e As
System.EventArgs) Handles BtnCancel.Click
Try
Catch
ex As Exception
Classlogger.LogInfo(ex)
End Try
End Sub
No comments:
Post a Comment