Created
January 11, 2017 04:44
-
-
Save jasoma/ef3bab14f67c979445351bf3adbfb590 to your computer and use it in GitHub Desktop.
NLog Programatic Config + Test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| using System.Text; | |
| using System.Threading; | |
| using System.Threading.Tasks; | |
| using NLog; | |
| using NLog.Targets; | |
| using NLog.Config; | |
| namespace CommonLogginTest | |
| { | |
| class Program | |
| { | |
| private static ILogger Log { get; set; } | |
| private static DateTime Startup = DateTime.Now; | |
| private static TimeSpan DeltaTime => DateTime.Now - Startup; | |
| static void Main(string[] args) | |
| { | |
| var config = new LoggingConfiguration(); | |
| var console = new ColoredConsoleTarget("console") { | |
| Layout = @"${date:format=HH\:mm\:ss} ${callsite}(${callsite-linenumber}) ${message} ${exception}" | |
| }; | |
| config.AddTarget(console); | |
| config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, LogLevel.Fatal, console)); | |
| var file = new FileTarget("file") { | |
| FileName = "logs/ndcmlog.txt", | |
| Encoding = Encoding.UTF8, | |
| ArchiveEvery = FileArchivePeriod.Minute, | |
| ArchiveOldFileOnStartup = true | |
| }; | |
| config.AddTarget(file); | |
| config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, LogLevel.Fatal, file)); | |
| LogManager.Configuration = config; | |
| Log = LogManager.GetCurrentClassLogger(); | |
| while (DeltaTime < TimeSpan.FromMinutes(2)) { | |
| Log.Debug("Debug"); | |
| error(); | |
| Thread.Sleep(TimeSpan.FromSeconds(10)); | |
| } | |
| Log.Fatal("Closing"); | |
| Console.WriteLine("> Done <"); | |
| Console.ReadLine(); | |
| } | |
| private static void error() { | |
| try { | |
| throw new Exception("It failed!"); | |
| } | |
| catch (Exception ex) { | |
| Log.Warn(ex, "Uh-oh!"); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment