Skip to content

Instantly share code, notes, and snippets.

@elpatron68
Forked from rstackhouse/gist:1162357
Last active August 29, 2015 14:24
Show Gist options
  • Save elpatron68/787969fd9010e5863908 to your computer and use it in GitHub Desktop.
Save elpatron68/787969fd9010e5863908 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NLog;
using NLog.Common;
using NLog.Targets;
using NLog.Config;
namespace ConsoleApplication1
{
class Program
{
private static Logger _logger;
static void Main(string[] args)
{
//InternalLogger.LogToConsole = true;
//InternalLogger.LogLevel = LogLevel.Trace;
var config = new LoggingConfiguration();
var target =
new FileTarget{
FileName=typeof(Program).FullName + ".log"
};
config.AddTarget("logfile", target);
var dbTarget = new DatabaseTarget();
dbTarget.ConnectionString = @"<server>;Initial Catalog=<database>;Persist Security Info=True;User ID=<user>;Password=<password>";
dbTarget.CommandText =
@"INSERT INTO [Log] (Date, Thread, Level, Logger, Message, Exception)
VALUES(GETDATE(), @thread, @level, @logger, @message, @exception)";
dbTarget.Parameters.Add(new DatabaseParameterInfo("@thread", new NLog.Layouts.SimpleLayout("${threadid}")));
dbTarget.Parameters.Add(new DatabaseParameterInfo("@level", new NLog.Layouts.SimpleLayout("${level}")));
dbTarget.Parameters.Add(new DatabaseParameterInfo("@logger", new NLog.Layouts.SimpleLayout("${logger}")));
dbTarget.Parameters.Add(new DatabaseParameterInfo("@message", new NLog.Layouts.SimpleLayout("${message}")));
dbTarget.Parameters.Add(new DatabaseParameterInfo("@exception", new NLog.Layouts.SimpleLayout("${exception}")));
config.AddTarget("database", dbTarget);
var rule = new LoggingRule("*", LogLevel.Debug, target);
config.LoggingRules.Add(rule);
var dbRule = new LoggingRule("*", LogLevel.Debug, dbTarget);
config.LoggingRules.Add(dbRule);
LogManager.Configuration = config; //doesn't work if moved after instatiation of config
_logger = LogManager.GetCurrentClassLogger();
_logger.Debug("Using programmatic config");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment