r/visualbasic • VB Guru • Apr 20 '15

Logging, do it or regret it later.

When a program starts getting ready for release to uses, it invariably happens that a developer thinks. We should probably have a log system so we know what happens when users use the machine. While this is correct it is way too late to be thinking about logging when the release is just around the corner.

This usually leads to a team member saying he can roll a logger in a "Couple of Hours". Which usually causes complete meltdown later on :)

I have a saying (#3 in my programmers list of programming) "Log early, and log often"

This means install your damn logging system early. I do this in my project creation step before the first commit to source control. Log often means log everything, albeit log important stuff with a higher level and the less import stuff lower down.

I have rolled my own logger, and in some cases still do if the project is an oddball. In most cases I use log4net. Log4net has been around a long time, has a great license (Apache License, Version 2.0) and is very easy to use in .NET.

It supports just about any type of logging you want;

Type										Description
-------------------------------------------------------------------------------------
log4net.Appender.AdoNetAppender				Writes logging events to a database using either prepared statements or stored procedures.
log4net.Appender.AnsiColorTerminalAppender	Writes color highlighted logging events to a an ANSI terminal window.
log4net.Appender.AspNetTraceAppender		Writes logging events to the ASP trace context. These can then be rendered at the end of the ASP page or on the ASP trace page.
log4net.Appender.ColoredConsoleAppender		Writes color highlighted logging events to the application's Windows Console.
log4net.Appender.ConsoleAppender			Writes logging events to the application's Console. The events may go to either the standard our stream or the standard error stream.
log4net.Appender.DebugAppender				Writes logging events to the .NET system.
log4net.Appender.EventLogAppender			Writes logging events to the Windows Event Log.
log4net.Appender.FileAppender				Writes logging events to a file in the file system.
log4net.Appender.LocalSyslogAppender		Writes logging events to the local syslog service (UNIX only).
log4net.Appender.MemoryAppender				Stores logging events in an in memory buffer.
log4net.Appender.NetSendAppender			Writes logging events to the Windows Messenger service. These messages are displayed in a dialog on a users terminal.
log4net.Appender.OutputDebugStringAppender	Writes logging events to the debugger. 
log4net.Appender.RemoteSyslogAppender		Writes logging events to a remote syslog service using UDP networking.
log4net.Appender.RemotingAppender			Writes logging events to a remoting sink using .NET remoting.
log4net.Appender.RollingFileAppender		Writes logging events to a file in the file system. The RollingFileAppender can be configured to log to multiple files based upon date or file size constraints.
log4net.Appender.SmtpAppender				Sends logging events to an email address.
log4net.Appender.SmtpPickupDirAppender		Sends logging events to an email address but writes the emails to a configurable directory rather than sending them directly via SMTP.
log4net.Appender.TelnetAppender				Clients connect via Telnet to receive logging events.
log4net.Appender.TraceAppender				Writes logging events to the .NET trace system.
log4net.Appender.UdpAppender				Sends logging events as connectionless UDP datagrams to a remote host or a multicast group using a UdpClient.

To use it is a simple as PIE, figure out what type of logging you want to do. I use Database logging for it makes it easier to query later, but it depends upon the project and info you need to log. Reference the log4net dll and do something like this;

Imports System

' Configure log4net using the .config file
<Assembly: log4net.Config.XmlConfigurator(Watch:=True)> 
' This will cause log4net to look for a configuration file
' called ConsoleApp.exe.config in the application base
' directory (i.e. the directory containing ConsoleApp.exe)

Namespace ConsoleApp
	' Example of how to simply configure and use log4net
	Public Class LoggingExample
		' Create a logger for use in this class
		Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
		' NOTE that using System.Reflection.MethodBase.GetCurrentMethod().DeclaringType
		' is equivalent to typeof(LoggingExample) but is more portable
		' i.e. you can copy the code directly into another class without
		' needing to edit the code.

		' Application entry point
		Public Shared Sub Main(Byval args As String())
			' Log an info level message
			If log.IsInfoEnabled Then log.Info("Application [ConsoleApp] Start")

			' Log a debug message. Test if debug is enabled before
			' attempting to log the message. This is not required but
			' can make running without logging faster.
			If log.IsDebugEnabled Then log.Debug("This is a debug message")

			Try
				Bar()
			Catch ex As Exception
				' Log an error with an exception
				log.Error("Exception thrown from method Bar", ex)
			End Try

			log.Error("Hey this is an error!")

			Dim disposableFrame As IDisposable

			Try 
				' Push a message on to the Nested Diagnostic Context stack
				disposableFrame = log4net.NDC.Push("NDC_Message")

				log.Warn("This should have an NDC message")

				' Set a Mapped Diagnostic Context value  
				log4net.MDC.Set("auth", "auth-none")
				log.Warn("This should have an MDC message for the key 'auth'")
			Finally
				' The NDC message is popped off the stack by using the Dispose method
				If (Not disposableFrame is Nothing) Then disposableFrame.Dispose()
			End Try

			log.Warn("See the NDC has been popped of! The MDC 'auth' key is still with us.")

			' Log an info level message
			If log.IsInfoEnabled Then log.Info("Application [ConsoleApp] End")

			Console.Write("Press Enter to exit...")
			Console.ReadLine()
		End Sub

		' Helper methods to demonstrate location information and nested exceptions

		Private Shared Sub Bar()
			Goo()
		End Sub

		Private Shared Sub Foo()
			Throw new Exception("This is an Exception")
		End Sub

		Private Shared Sub Goo()
			Try
				Foo()
			Catch ex As Exception
				Throw New ArithmeticException("Failed in Goo. Calling Foo. Inner Exception provided", ex)
			End Try
		End Sub
	End Class

There are other loggers I just showed the one I am most familiar with (and the most commonly used) If you take anything away from this it should be "Log Early, and Log Often"

Bone

5 Upvotes

16 comments sorted by

2

u/Vanquiishh VB.Net Beginner Apr 26 '15 edited Apr 26 '15

I haven't gotten to ASP.net yet, but in my current VB.net course, and also in the Java my teacher/program director has been making us use a log modual procedure that he created in every single procedure in the projects, because every procedure is an important procedure. So i'd recommend using it everywhere out of habit? even if an error can't occur. That's what i've been taught.

Anyways, the idea behind it is when an error is encountered by the user and they instantly click ok or whatever, getting rid of the messagebox before they call tech support(with no way to explain it), it'll save the error message and information to a logfile in the program's directory.

So when the person calls tech support all you have to do is hope they can find the directory where it's installed, and then have them email you the most recent log file. Here's the code:

EDIT: Added it:

Public Module modUtilities

	' --------------------------------------------------------------------------------
	' Constants
	' --------------------------------------------------------------------------------
	' What log file should we use
	Private Const strLOG_FILE_EXTENSION As String = ".Log"

	' --------------------------------------------------------------------------------
	' Properties
	' --------------------------------------------------------------------------------
	Private m_strOldLogFilePath As String           ' Name of the last log file opened
	Private m_fsLogFile As FileStream = Nothing     ' File handle of the last log file opened
	
	
	
	' ----------------------------------------------------------------------
	' ----------------------------------------------------------------------
	' WriteLog
	' ----------------------------------------------------------------------
	' ----------------------------------------------------------------------

	' What is WriteLog?  It's a procedure that will write an exception or
	' string to a disk file.  The file is named with the current date using
	' yyyymmdd format (so it sorts correctly).  The file is created in a Log
	' directory off of the current working director (usually where the executable
	' was launched from).
	' 
	' Why use WriteLog?  Because when, not if, the user gets an error you 
	' (the programmer) are going to need the error information to be able
	' to find and fix the bug in a reasonable period of time.  The exception
	' will tell you where the error happened and, if you're lucky, why it
	' happened.
	' 
	' How to use?  Wrap procedure code in a try/catch block and put
	' a call to WriteLog in the catch block.  You really can't do much else
	' at that point because you don't know why the error happened.  If you
	' expect an error you should code for it.  So this is only for errors
	' you don't expect and don't know about.
	' 
	' When to use?  When, not if, the technical support phone rings, what 
	' percentage of the time do you want the exception information to help
	' you find and fix the problem?  I want it 100%.  That means I have
	' to use try/catch block with WriteLog in 100% of my procedures.
	' 
	' Guidelines for try/catch:
	' 1) Use in all procedures
	' 2) ALL code goes in the try block with two exceptions.  If it's a function
	'    the return variable, and only the return variable, is declared 
	'    immediately before the try block and the return is immediately
	'    after the catch block.
	' 3) Do as little as possible in the catch block so that you don't
	'    cause another exception.
	' 4) Use only one try/catch block per procedure.  If you expect
	'    an error then code for it.  Don't use an empty catch block as
	'    a crutch to ignore the error.



	' --------------------------------------------------------------------------------
	' Name: WriteLog
	' Abstract: Overload with blnDisplay set to true
	' --------------------------------------------------------------------------------
	Public Sub WriteLog(ByVal excErrorToLog As Exception, Optional ByVal blnDisplayWarning As Boolean = True)

		Try

			WriteLog(excErrorToLog.ToString(), blnDisplayWarning)

		Catch excError As Exception

			' Log and display error message
			MessageBox.Show("Error:" & vbNewLine & excError.ToString(), Application.ProductName, _
							MessageBoxButtons.OK, MessageBoxIcon.Warning)

		End Try

	End Sub



	' --------------------------------------------------------------------------------
	' Name: WriteLog
	' Abstract: Write a message to the error log.
	' --------------------------------------------------------------------------------
	Public Sub WriteLog(ByVal strMessageToLog As String, Optional ByVal blnDisplayWarning As Boolean = True)

		Try

			Dim fsLogFile As FileStream = Nothing
			Dim encConvertToByteArray As New System.Text.UTF8Encoding

			' Warn the user?
			If blnDisplayWarning = True Then

				' Yes( ProductName is set in AssemblyInfo )
				MessageBox.Show(strMessageToLog, Application.ProductName, _
								MessageBoxButtons.OK, MessageBoxIcon.Warning)

			End If

			' Append a date/time stamp
			strMessageToLog = (DateTime.Now).ToString("yyyy/MM/dd HH:mm:ss") & " - " & strMessageToLog & vbNewLine & _
							  vbNewLine

			' Get a free file handle
			fsLogFile = GetLogFile()

			' Is the file OK?
			If Not fsLogFile Is Nothing Then

				' Yes, Log it
				fsLogFile.Write(encConvertToByteArray.GetBytes(strMessageToLog), 0, strMessageToLog.Length)

				' Flush the buffer so we can immediately see results in file.  Very important.
				' Otherwise we have to wait for flush which might be when application closes
				' or we get another error.  Waiting for the application to close may not be
				' a good idea if the application is in a production environment (e.g. a web app
				' running on a remote server)
				fsLogFile.Flush()

			End If

		Catch excError As Exception

			' Log and display error message
			MessageBox.Show("Error:" & vbNewLine & excError.ToString(), Application.ProductName, _
							MessageBoxButtons.OK, MessageBoxIcon.Warning)

		End Try

	End Sub



	' --------------------------------------------------------------------------------
	' Name: DeleteOldFiles
	' Abstract: Delete any files older than 10 days.
	' --------------------------------------------------------------------------------
	Private Sub DeleteOldFiles()

		Try

			Dim strLogFilePath As String = ""
			Dim dirLogDirectory As DirectoryInfo = Nothing
			Dim dtmFileCreated As DateTime = Now
			Dim intDaysOld As Integer = 0

			' Path
			strLogFilePath = Application.StartupPath & "\Log\"

			' Look for any files
			dirLogDirectory = New DirectoryInfo(strLogFilePath)

			' Are there any?
			For Each finLogFile As FileInfo In dirLogDirectory.GetFiles("*" & strLOG_FILE_EXTENSION)

				' When was the file created?
				dtmFileCreated = finLogFile.CreationTime

				' How old is the file?
				intDaysOld = (dtmFileCreated.Subtract(DateTime.Now)).Days

				' Is the file older than 10 days?
				If intDaysOld > 10 Then

					' Yes.  Delete it.
					finLogFile.Delete()

				End If

			Next

		Catch excError As Exception

			' Log and display error message
			MessageBox.Show("Error:" & vbNewLine & excError.ToString(), Application.ProductName, _
							MessageBoxButtons.OK, MessageBoxIcon.Warning)

		End Try

	End Sub



	' --------------------------------------------------------------------------------
	' Name: GetLogFile
	' Abstract: Open the log file for writing.  Use today's date as part of
	'           the file name.  Each day a new log file will be created.
	'           Makes debug easier.
	'           Use a filestream object so we can specify file read share
	'           during the open call.
	' --------------------------------------------------------------------------------
	Private Function GetLogFile() As FileStream

		Try
			Dim strToday As String = (DateTime.Now).ToString("yyyyMMdd")
			Dim strLogFilePath As String = ""

			' Log everything in a log directory off of the current application directory
			strLogFilePath = Application.StartupPath & "\Log\" & strToday & strLOG_FILE_EXTENSION

			' Is this a new day?
			If m_strOldLogFilePath <> strLogFilePath Then

				' Save the log file name
				m_strOldLogFilePath = strLogFilePath

				' Does the log directory exist?
				If Directory.Exists(Application.StartupPath & "\Log") = False Then

					' No, so create it
					Directory.CreateDirectory(Application.StartupPath & "\Log")

				End If

				' Close old log file( if there is one )
				If Not m_fsLogFile Is Nothing Then m_fsLogFile.Close()

				' Delete old log files
				DeleteOldFiles()

				' Does the file exist?
				If File.Exists(strLogFilePath) = False Then

					' No, create with shared read access so it can be read while application has it open
					m_fsLogFile = New FileStream(strLogFilePath, FileMode.Create, FileAccess.Write, FileShare.Read)

				Else

					' Yes, append with shared read access so it can be read while application has it open
					m_fsLogFile = New FileStream(strLogFilePath, FileMode.Append, FileAccess.Write, FileShare.Read)

				End If

			End If

		Catch excError As Exception

			' Log and display error message
			MessageBox.Show("Error:" & vbNewLine & excError.ToString(), Application.ProductName, _
							MessageBoxButtons.OK, MessageBoxIcon.Warning)

		End Try

		' Return result
		Return m_fsLogFile

	End Function

#End Region

3

u/Bonejob VB Guru Apr 26 '15

place 4 spaces in front of each line of your code. I use notepad++ cut as paste it in their. THen I can select all and press tab to get the 4 spaces. takes 1 min.

1

u/[deleted] Apr 27 '15

Thanks. I posted it.

4

u/hdsrob Apr 20 '15 edited Apr 21 '15

Agree completely.

I released my very first VB6 production app in 2003 with almost no experience in real development (my company bought a nearly complete code base from a vendor that I finished for release).

3 hours later I got my first bug report, which consisted of "we were doing something, and it crashed". ... no error message, no idea exactly what they were doing, just some lost data. The hits kept on coming, and I quickly learned both defensive programing (one crash was due to the user entering a "$" in a textbox that was converting straight to currency) and error handling.

Within a month, I had a functional logging system, and had wrapped every sub or function with an "On Error GoTo" routine, and had built an MZTools Template for easily inserting Error Handling into code.

Today, it's all been converted to .NET (nearly 500K LOC), and the error handling system is at the core. It's now a Windows Service, and errors / trace data are passed to it from various services and apps in our suite (via a socket connection, using an XML message format). Logs are stored for 30 days on site, and logs from current versions are zipped and transferred back to our server at night so that we can go through them proactively.

IMO a function or sub without a Try / Catch block is unfinished, and allowing the end user to see one of those "there was a problem with xyz.exe and it has to close" windows should be avoided at all cost.

2

u/CalvinR VB.Net Master Apr 21 '15

I disagree 100% in your statement that a function without a try catch is incomplete.

You should only catch errors when you expect to handle them. Also it makes no sense to have a try catch when no exceptions can occur.

If all you plan on doing is logging your error you should let it bubble up to your global exception handler so you get the full stack trace for when the error happened.

I agree with you in the importance of logging however, and of being proactive in looking at your logs.

1

u/hdsrob Apr 21 '15

I should have said, "non trivial" subs and functions, as we don't handle in those (where no error can occur).

There are a few places where we need higher levels of stack trace (usually in dealing with third party tools), or can't reach the logging system without breaking encapsulation, and we intentionally don't handle these, but these really are the exception.

Keep in mind, I'm not talking about throwing / rethrowing errors back up the stack, but logging the state of the app where we are, and in most cases, resetting state or returning statuses to ensure that the rest of the application can continue to run (so both logging, and while not handling the error directly, handling the result of the error).

We never allow the app to shut down / need a restart due to an error if possible.

1

u/CalvinR VB.Net Master Apr 21 '15

That sounds good, I know I might come across as pedantic but I find that beginning developers when they hear a piece of advice from a more advanced dev will tend to follow it carte blanche without actually understanding why.

So when you said Every Sub and Function they will take that to mean literally every sub and function should have a try catch and should log.

I'm actually in the situation now where I'm tasked with improving the process and the code of our developers.

My biggest hurdle trying to break the bad habits of our developers in my department and get them to improve the code they write. The problem is that about ten years ago a group of advanced devs with a background in C and C++ set the standards and gave the initial training for .Net languages and the bad habits have stuck around.

For instance I'm having a bitch of a time convincing the devs the following:

  • Not to set ints and floats to 0 when they first declare them as they are already set

  • Not to wrap every method in a try catch and set all variables declared inside of it to Nothing/null so that they get cleaned up properly

  • Not to declare all variables at the top of every method instead of right before they are used.

And that's just a tiny fraction of the bad coding habits I have to break.

1

u/icehawke VB.Net Advanced Apr 21 '15

•Not to declare all variables at the top of every method instead of right before they are used.

Not only a C/C++ thing. I still do this. Especially with variables I know will be used throughout the sub/function. I have managed to wean myself off this for most other variables.

1

u/CalvinR VB.Net Master Apr 21 '15

The only reason it should be at the top is if you use the variable directly after.

It's a bad habit to get into because it makes it more difficult to maintain the code.

1

u/icehawke VB.Net Advanced Apr 21 '15

It's a habit I got into in the early 90s :)

1

u/CalvinR VB.Net Master Apr 21 '15

That's the problem it's a habit that's hard to break, it would be nice if there was a rule in the built in FXCop for visual studio to watch for that.

1

u/icehawke VB.Net Advanced Apr 21 '15

I use ReSharper and it doesn't squawk about it either.

1

u/CalvinR VB.Net Master Apr 21 '15

Nope though I expect we might see something come eventually through Roslyn but I don't know it might be too hard of a but to crack.

2

u/CalvinR VB.Net Master Apr 21 '15

Look into nlog, I know we evaluated several .net logging systems and found blog was the one that worked for me.

I've heard good things about common.logging as well the ability to abstract away your logging framework is pretty powerful.

1

u/icehawke VB.Net Advanced Apr 21 '15

I rolled my own for my current project. It was the first (okay, maybe second) bit of code I wrote.

It writes to one of four different log files depending on what's being logged. Since this is a game, there is a Game log for each game with game specific logging, there is a Race log for each specific race, an Error log for errors and a General log for general non-game/race specific information.

The application has a built-in log viewer with a "copy to clipboard" functionality. This allows people to send me a log without needing to dig up the file on the drive and send that to me.

1

u/heeero Apr 20 '15

Well said. Now, if I can convince my developer who insists on msgbox() , I'll be all set.