JavaBlog.fr / Java.lu C#,DEVELOPMENT CSharp/C# : Custom Logging Service With NLog

CSharp/C# : Custom Logging Service With NLog

Hi,

Here, an simple example of use of logging platform NLog in C# projects. Or course, you need add reference to Nlog package in your project via NuGet Package Manager.

NLog is a free logging platform for .NET, NETSTANDARD, Xamarin, Silverlight and Windows Phone with rich log routing and management capabilities. NLog makes it easy to produce and manage high-quality logs for your application regardless of its size or complexity.

using System;
using NLog;
using NLog.Config;
using NLog.Targets;
using System.IO;
using System.Collections.ObjectModel;
using NLog.Layouts;

namespace HuoBlog.Logging
{

    public static class LoggerService
    {
        private static Logger logger;
        private static readonly string LOGGER_TARGET_FILE_NAME = "file";

        public static string ForceNewLoggerFile(string logFilePath = null)
        {
            logger = null;
            GetLogger(logFilePath);
            return GetLogFilePath();
        }

        public static string GetLogFilePath()
        {
            string logFilePath = null;
            if(logger != null)
            {
                foreach (Target target in LogManager.Configuration.AllTargets)
                {
                    if (target.GetType() == typeof(FileTarget) 
                        && ((FileTarget)target).FileName.GetType() == typeof(SimpleLayout))
                    {
                        SimpleLayout layout = (SimpleLayout) ((FileTarget)target).FileName;
                        return layout.Text;
                    }
                }
            }

            return logFilePath;
        }

        private static Logger GetLogger(string logFilePath = null)
        {
            if (logger == null)
            {
                // Log file
                {
                    if(logFilePath == null) // Generate a logfile
                    {
                        // OLD : 
                        //string outputPath = Path.Combine(Environment.CurrentDirectory, "output");
                        //if (!Directory.Exists(outputPath))
                        //    Directory.CreateDirectory(Path.Combine(Environment.CurrentDirectory, "output"));
                        // NEW: 
                        string outputPath = Environment.CurrentDirectory;
                        logFilePath = Path.Combine(outputPath, "HuoBlog_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".log");
                    }
                }

                // Config logger
                {
                    var config = new LoggingConfiguration();
                    var fileTarget = new FileTarget();
                    fileTarget.FileName = logFilePath;
                    fileTarget.Layout = "${message}";
                    config.AddTarget(LOGGER_TARGET_FILE_NAME, fileTarget);
                    config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, fileTarget));
                    LogManager.Configuration = config;
                }

                logger = LogManager.GetLogger("Extract");
            }

            return logger;
        }

        public static void Info(string message)
        {
            GetLogger().Info("INFO: " + message);
        }

        public static void Warn(string message)
        {
            GetLogger().Warn("WARNING: " + message);
        }

        public static void Error(string message)
        {
            GetLogger().Error("ERROR: " + message);
        }

        public static void Print(string message)
        {
            GetLogger().Info(message);
        }
        
    }
}

….

try{
	string logFilePath = LoggerService.ForceNewLoggerFile();
	// ...	

	LoggerService.Info("############ HuoBlog - Started at " + DateTime.Now);
	LoggerService.Print("\n\n");
	// ...	
}
catch (Exception ex)
{
	LoggerService.Error(ex.ToString());
}
finally
{
	LoggerService.Info("############ HuoBlog - ended at " + DateTime.Now);
	// ...	
	string logFileContent = File.ReadAllText(LoggerService.GetLogFilePath());
	// ...	
}

C:\Workspaces\MS_Visual_Studio_Projects\…\bin\Debug\output\HuoBlog_20171120165730.log.

That’s all!!

Huseyin

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

Related Post