Skip to content

Instantly share code, notes, and snippets.

@MiloszKrajewski
Last active April 30, 2017 09:26
Show Gist options
  • Save MiloszKrajewski/fc6582eab278f02bd6c096bbff83f535 to your computer and use it in GitHub Desktop.
Save MiloszKrajewski/fc6582eab278f02bd6c096bbff83f535 to your computer and use it in GitHub Desktop.
using NLog;
using NLog.Config;
using NLog.Targets;
using System.IO;
namespace ProductName
{
class Program
{
static void Main(string[] args)
{
ConfigureLogging(Path.GetFullPath("."), "ProductName");
}
private static void ConfigureLogging(string folder, string productName)
{
var config = new LoggingConfiguration();
ConfigureConsoleLogging(config);
ConfigureFileLogging(config, folder, productName);
LogManager.Configuration = config;
}
private static void ConfigureFileLogging(
LoggingConfiguration config, string folder, string productName)
{
Directory.CreateDirectory(folder);
var target = new FileTarget()
{
Name = "file",
Layout = "${date:format=yyyyMMdd.HHmmss} ${threadid}> [${level}] (${logger}) ${message}",
ArchiveEvery = FileArchivePeriod.Day,
MaxArchiveFiles = 7,
FileName = Path.Combine(folder, productName + ".log"),
ArchiveFileName = Path.Combine(folder, productName + ".bak"),
};
config.AddTarget("file", target);
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, target));
}
private static void ConfigureConsoleLogging(LoggingConfiguration config)
{
var console = new ColoredConsoleTarget
{
Name = "console",
Layout = "${message}",
UseDefaultRowHighlightingRules = true,
ErrorStream = false,
};
Action<LogLevel, ConsoleOutputColor> configure = (level, color) =>
{
console.RowHighlightingRules.Add(
new ConsoleRowHighlightingRule(
$"level == LogLevel.{level}",
color,
ConsoleOutputColor.NoChange));
};
configure(LogLevel.Trace, ConsoleOutputColor.DarkGray);
configure(LogLevel.Debug, ConsoleOutputColor.Gray);
configure(LogLevel.Info, ConsoleOutputColor.Cyan);
configure(LogLevel.Warn, ConsoleOutputColor.Yellow);
configure(LogLevel.Error, ConsoleOutputColor.Red);
configure(LogLevel.Fatal, ConsoleOutputColor.Magenta);
config.AddTarget("console", console);
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, console));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment