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.

01using System;
02using NLog;
03using NLog.Config;
04using NLog.Targets;
05using System.IO;
06using System.Collections.ObjectModel;
07using NLog.Layouts;
08 
09namespace HuoBlog.Logging
10{
11 
12    public static class LoggerService
13    {
14        private static Logger logger;
15        private static readonly string LOGGER_TARGET_FILE_NAME = "file";
16 
17        public static string ForceNewLoggerFile(string logFilePath = null)
18        {
19            logger = null;
20            GetLogger(logFilePath);
21            return GetLogFilePath();
22        }
23 
24        public static string GetLogFilePath()
25        {
26            string logFilePath = null;
27            if(logger != null)
28            {
29                foreach (Target target in LogManager.Configuration.AllTargets)
30                {
31                    if (target.GetType() == typeof(FileTarget)
32                        && ((FileTarget)target).FileName.GetType() == typeof(SimpleLayout))
33                    {
34                        SimpleLayout layout = (SimpleLayout) ((FileTarget)target).FileName;
35                        return layout.Text;
36                    }
37                }
38            }
39 
40            return logFilePath;
41        }
42 
43        private static Logger GetLogger(string logFilePath = null)
44        {
45            if (logger == null)
46            {
47                // Log file
48                {
49                    if(logFilePath == null) // Generate a logfile
50                    {
51                        // OLD :
52                        //string outputPath = Path.Combine(Environment.CurrentDirectory, "output");
53                        //if (!Directory.Exists(outputPath))
54                        //    Directory.CreateDirectory(Path.Combine(Environment.CurrentDirectory, "output"));
55                        // NEW:
56                        string outputPath = Environment.CurrentDirectory;
57                        logFilePath = Path.Combine(outputPath, "HuoBlog_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".log");
58                    }
59                }
60 
61                // Config logger
62                {
63                    var config = new LoggingConfiguration();
64                    var fileTarget = new FileTarget();
65                    fileTarget.FileName = logFilePath;
66                    fileTarget.Layout = "${message}";
67                    config.AddTarget(LOGGER_TARGET_FILE_NAME, fileTarget);
68                    config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, fileTarget));
69                    LogManager.Configuration = config;
70                }
71 
72                logger = LogManager.GetLogger("Extract");
73            }
74 
75            return logger;
76        }
77 
78        public static void Info(string message)
79        {
80            GetLogger().Info("INFO: " + message);
81        }
82 
83        public static void Warn(string message)
84        {
85            GetLogger().Warn("WARNING: " + message);
86        }
87 
88        public static void Error(string message)
89        {
90            GetLogger().Error("ERROR: " + message);
91        }
92 
93        public static void Print(string message)
94        {
95            GetLogger().Info(message);
96        }
97         
98    }
99}

….

01try{
02    string logFilePath = LoggerService.ForceNewLoggerFile();
03    // ... 
04 
05    LoggerService.Info("############ HuoBlog - Started at " + DateTime.Now);
06    LoggerService.Print("\n\n");
07    // ... 
08}
09catch (Exception ex)
10{
11    LoggerService.Error(ex.ToString());
12}
13finally
14{
15    LoggerService.Info("############ HuoBlog - ended at " + DateTime.Now);
16    // ... 
17    string logFileContent = File.ReadAllText(LoggerService.GetLogFilePath());
18    // ... 
19}

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