Home > VB.NET > Logging Messages Sent to a Listbox or Logfile

Logging Messages Sent to a Listbox or Logfile

Many long running applications may have a need to output the progress and messages to a Listbox to provide feedback instead of using a Logging Framework such as NLog.  I like to use a helper Function that writes these messages to a Listbox and logfile with an option to log them to a file only.

Public Function AddLBMessage(ByVal TextMessage As String, Optional ByVal LogOnly As Boolean = False) As Boolean
Try
Dim _LogFilename As String

TextMessage = String.Format("{0}: {1}", Now, TextMessage)

_LogFilename = String.Format("{0}\Logs\{1}", Application.StartupPath, Format(Now, "yyyy-MM"))

If Directory.Exists(_LogFilename) = False Then
Directory.CreateDirectory(_LogFilename)
End If

_LogFilename &= String.Format("\{0}-ProcessLogfile.txt", Format(Now, "yyyy-MM-dd"))

My.Computer.FileSystem.WriteAllText(_LogFilename, TextMessage & vbNewLine, True, System.Text.Encoding.ASCII)

If lstMessages.Items.Count > 500 Then
lstMessages.Items.RemoveAt(0)
End If

If Not LogOnly Then
lstMessages.Items.Add(TextMessage)
End If
lstMessages.SelectedIndex = lstMessages.Items.Count - 1

Application.DoEvents()
Return True

Catch ex As Exception
MessageBox.Show(ex.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Function
Advertisements
Categories: VB.NET Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: