To add activity logging feature on your VB.NET application, follow these steps:
1. Add an application settings item with a name of "LogPath" and type as string. This setting will hold the path of the log file to be created. (To add a setting, just double click "My Project" from the solution explorer and then click Settings from the tabs on the left.)
2. Add a textbox on the form you want to add the transaction logger. On my sample project, I named it as "txtLogs".
3. Include the following namespace.
Imports System.IO
Imports LogFileSample.My 'To access the project settings
4. Copy and Paste the following functions.
'''
''' Write the transaction/activity on the textbox
'''
''' the message you want to log
''' color to use
'''
Private Sub WriteLog(ByVal msg As String, ByVal iColor As Color)
logcount = logcount + 1
txtLogs.SelectionColor = iColor
txtLogs.AppendText("[" + DateTime.Now.ToString() + "] " & msg & vbNewLine)
If Not txtLogs.Focused Then txtLogs.Focus()
End Sub
'''
''' Save the transaction logs from the textbox to a log file
'''
'''
Private Sub SaveLog()
If MySettings.Default.LogPath.Length > 0 Then
Try
txtLogs.SaveFile(MySettings.Default.LogPath & "\" & Format(DateTime.Now, "M-d-yy h.mtt") & ".log")
txtLogs.Clear()
WriteLog("Log was successfully saved at " & MySettings.Default.LogPath & "\" & Format(DateTime.Now, "M-d-yy h.mtt") & ".log", Color.DarkBlue)
Catch ex As Exception
WriteLog("Error saving log...", Color.Red)
End Try
End If
End Sub
5. Now to display a transaction on the textbox we added earlier, call WriteLog and to save it as log file, invoke the SaveLog function.
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
WriteLog("Log Sample Project Started", Color.Black)
End Sub
Private Sub btnSaveLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveLog.Click
SaveLog()
End Sub

Download the VB.NET (2008) sample project via [mediafire]
For More Coding Tips & Tricks, subscribe now.
4 comments:
Can you please post a video how to do that because i tried and it doesn't work.
Thanks
tony.fonseca1@gmail.com
Hi try to download the the sample project. It should work. If not please post the error here. Thanks
I downloaded the project and included it in my application but the LogfileSample.My import statement isn't being recognised hence giving errors for Mysettings.What should i do.
Hi the "LogfileSample.My" is the orginal project name setting. You changed it to your project/namespace name
Post a Comment