Monday, March 24, 2014

Choosing Logging Library for .Net : NLog

When it comes to logging, printing it out yourself to console or file probably the most straightforward way. However, if you want to get more structured in your log, with level and flexible on/of switching you'll need a more dedicated logging library. However, like any library, choosing the sweet spot where you get the feature you want but with the least complexity and learning curve can be challenging.

As for logging, when I research around the two that pop up most is log4net and NLog. The choise is pretty simple though, log4net is good but pretty outdated now while NLog is quite active, well-supported has rich feature. So, the choice goes to NLog.

Quick Usage :

After you link the library (using NuGet or manually). Declare the logger in your class :

private static Logger logger = LogManager.GetCurrentClassLogger();

and call at the place that needed it :

logger.Debug("log message");

You can add a lot of additional details to your log with its predefined variables. You can consult the manual to see what is available. Also, since you declare logger on each class, it can automatically  print in which class and the point where the log is called. It is quite useful for debugging.

No comments: