r/visualbasic • u/Bonejob 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 ClassThere 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
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.
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: