using nLog in C#

Finally I had a new project were I needed some logging and on opportunity to use nLog for the first time. I have wanted to check it out in the past but it just never came to that. So here is the quick run down, the sample is from their tutorial with a slight mods from me and is really all you need to get nLog up and running quickly.

//
using NLog;
using NLog.Targets;
using NLog.Config;
using NLog.Win32.Targets;

            // Step 1. Create configuration object
            LoggingConfiguration config = new LoggingConfiguration();

            // Step 2. Create targets and add them to the configuration
            ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();
            config.AddTarget(“console”, consoleTarget);
            //
            FileTarget fileTarget = new FileTarget();
            config.AddTarget(“file”, fileTarget);

            // Step 3. Set target properties
            consoleTarget.Layout = “${date:format=HH\\:MM\\:ss}: ${message}”;
            // set the file
            fileTarget.FileName = CxUtil.getDataDir() + \\log.txt”;
            fileTarget.Layout = “${date:format=HH\\:MM\\:ss}: ${message}”;
            // don’t clutter the hard drive
            fileTarget.deleteOldFileOnStartup = true;

            // Step 4. Define rules
            LoggingRule rule1 = new LoggingRule(“*”, LogLevel.Debug, consoleTarget);
            config.LoggingRules.Add(rule1);
           
            // Only log to file in non debug mode
            #if !DEBUG
                LoggingRule rule2 = new LoggingRule(“*”, LogLevel.Debug, fileTarget);
                config.LoggingRules.Add(rule2);
            #endif

            // Step 5. Activate the configuration
            LogManager.Configuration = config;

            // Create logger
            Logger logger = LogManager.GetLogger(“Example”);
            // Example usage
            logger.Trace(“trace log message”);
            logger.Debug(“debug log message”);
            logger.Info(“info log message”);
            logger.Warn(“warn log message”);
            logger.Error(“error log message”);
            logger.Fatal(“fatal log message”);

3 Comments

  1. Adam says:

    Out of curiosity, why did you go with nLog? Does it have something log4net and the Logging application block from MSFT P&P don’t have?

  2. orn says:

    For me it’s simplicity, I looked at log4net before it just doesn’t seem straight forward to get going quickly . I didn’t even know about MSFT P&P / Microsoft.Practices.EnterpriseLibrary.Logging. Same thing there looking at it, it seems complicated. They even wrote an app to configure the thing. If all you need is simple logging nLog is great. If I need logging from a bigger system I might take a closer look at log4net and maybe the MS stuff.

  3. orn says:

    The layouts in the sample do not work anymore in a newer version of nlog ( 5.0.0-beta07 ). Skipping the layout lines will give you nice default output.

Leave a Reply