Skip to content

Instantly share code, notes, and snippets.

@jasoma
Created January 11, 2017 04:44
Show Gist options
  • Save jasoma/ef3bab14f67c979445351bf3adbfb590 to your computer and use it in GitHub Desktop.
Save jasoma/ef3bab14f67c979445351bf3adbfb590 to your computer and use it in GitHub Desktop.
NLog Programatic Config + Test
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