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.
06 | using System.Collections.ObjectModel; |
09 | namespace HuoBlog.Logging |
12 | public static class LoggerService |
14 | private static Logger logger; |
15 | private static readonly string LOGGER_TARGET_FILE_NAME = "file" ; |
17 | public static string ForceNewLoggerFile(string logFilePath = null ) |
20 | GetLogger(logFilePath); |
21 | return GetLogFilePath(); |
24 | public static string GetLogFilePath() |
26 | string logFilePath = null ; |
29 | foreach (Target target in LogManager.Configuration.AllTargets) |
31 | if (target.GetType() == typeof(FileTarget) |
32 | && ((FileTarget)target).FileName.GetType() == typeof(SimpleLayout)) |
34 | SimpleLayout layout = (SimpleLayout) ((FileTarget)target).FileName; |
43 | private static Logger GetLogger(string logFilePath = null ) |
49 | if (logFilePath == null ) |
56 | string outputPath = Environment.CurrentDirectory; |
57 | logFilePath = Path.Combine(outputPath, "HuoBlog_" + DateTime.Now.ToString( "yyyyMMddHHmmss" ) + ".log" ); |
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; |
72 | logger = LogManager.GetLogger( "Extract" ); |
78 | public static void Info(string message) |
80 | GetLogger().Info( "INFO: " + message); |
83 | public static void Warn(string message) |
85 | GetLogger().Warn( "WARNING: " + message); |
88 | public static void Error(string message) |
90 | GetLogger().Error( "ERROR: " + message); |
93 | public static void Print(string message) |
95 | GetLogger().Info(message); |
….
02 | string logFilePath = LoggerService.ForceNewLoggerFile(); |
05 | LoggerService.Info( "############ HuoBlog - Started at " + DateTime.Now); |
06 | LoggerService.Print( "\n\n" ); |
11 | LoggerService.Error(ex.ToString()); |
15 | LoggerService.Info( "############ HuoBlog - ended at " + DateTime.Now); |
17 | string logFileContent = File.ReadAllText(LoggerService.GetLogFilePath()); |
C:\Workspaces\MS_Visual_Studio_Projects\…\bin\Debug\output\HuoBlog_20171120165730.log.
That’s all!!
Huseyin
Related