Posts tagged ‘nLog’

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);
            // Only log to file in non debug mode
            #if !DEBUG
                LoggingRule rule2 = new LoggingRule(“*”, LogLevel.Debug, fileTarget);

            // 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”);