Loggers

Few months ago I went to the job interview. One of the final questions was:
– How do you log exceptions?
– I have a log folder where I store txt files with exception details and time when they occured.
– You don’t use any logging framework?
– Nope.
– We use log4net and NLog here.
– Hold on, I’ve got to write down this.

I always take notes when I’m at job interview. That helps me to become better programmer. If the result is good I could give them a label ‚Learn this so we can work more efficient together’. And if it’s bad – ‚Learn this and maybe next time we will hire you.’

NLog

As long as the framework does the job, I think you don’t need to look for an alternative. Don’t get me wrong – I love to learn new things, but you have to know where to use them. Try them in your pet projects first. I’ve decided to start off with NLog, because it looked more user-friendly. Maybe it’s because of a GitHub design, I hate these ugly Apache manuals. The installation was rapid, because it took me few lines of code to setup everything. The usage itself is also very easy. You just type Log.Debug(„message”) where Debug is a log level.

Log levels and targets

NLog and log4net has standard levels of notifying: Debug, Info, Warn, Error, Fatal. NLog also supports Trace level. The usage may differ with various teams, but for personal stuff I’d go:

  • Trace – very detailed debug logs.
  • Debug – debug. Do I really have to write more here?
  • Info – the messages you might want to see in logs. You can call it production debug.
  • Warn – for the errors that doesn’t matter much and user can handle, like timeouts.
  • Error – for exceptions. These must be redirected to a file, so you can read it later.
  • Fatal – when the error is so big the user cannot work further with the application.

The order here is important, because the logger you setup will also have access to lower levels. Eg. minimum level of Warn can also write Error and Fatal messages.

Redirecting logs to output might be difficult to read, because we often see a lot of messages there. I’ve decided to open it in Sentinel. I can fiter it as I want to – highlight specific types, or even hide the ones that I don’t need. You can setup many targets (or appenders in log4net). Each of them can be responsible for specific log levels and you can even point them where should they log (output, colored console, address etc.).

Playground

Get started by playing around with a tiny app, it’s always the best way to learn some new tech. I’ve got a task for you: Try to setup a main logger and play with 3 types of levels – Debug, Info and Error. For most of small apps that should be enough. Use Sentinel to display them. Create also a file logger for handling exceptions. And check out log4net – maybe you’ll like it more than me.

Till next time.