Previously my ASP .NET MVC5 application had error logging working great with the use of a nlog.config file. Now I want to move away from the config file approach; I want to configure Nlog programmatically and remove the need for the config file. The examples are good at showing me how to set it up programmatically, but I'm confused as to how to actually invoke the configuration class and actually implementing it. Heres what I have:
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
NALSPrincipal userInfo = (NALSPrincipal)Context.User;
// Step 1. Create configuration object
var config = new LoggingConfiguration();
// Step 2. Create targets and add them to the configuration
var fileTarget = new FileTarget();
config.AddTarget("file", fileTarget);
// Step 3. Set target properties
fileTarget.FileName = "C:/nlogFile.txt";
fileTarget.Layout = "Exception Type: ${exception:format=Type}${newline}
Target Site: ${event-context:TargetSite}${newline}
Message: ${message}";
// Step 4. Define rules
var rule2 = new LoggingRule("*", LogLevel.Trace, fileTarget);
config.LoggingRules.Add(rule2);
// Step 5. Activate the configuration
LogManager.Configuration = config;
Logger logger = LogManager.GetCurrentClassLogger();
LogEventInfo eventInfo = new LogEventInfo(LogLevel.Trace, "", logger.Name);
eventInfo.Properties["TargetSite"] = ex.TargetSite;
eventInfo.Exception = ex;
logger.Log(eventInfo);
}
Does anyone know what this isn't working? Heres the documentation I based this off of: https://github.com/nlog/NLog/wiki/Configuration-API
If it helps, here's what I had back when I used the nlog.config file and it worked fine:
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
NALSPrincipal userInfo = (NALSPrincipal)Context.User;
Logger logger = LogManager.GetCurrentClassLogger();
LogEventInfo eventInfo = new LogEventInfo(LogLevel.Trace, "", logger.Name);
eventInfo.Properties["CUID"] = userInfo.userDetails.ContactID;
eventInfo.Properties["Username"] = Context.User.Identity.Name;
eventInfo.Properties["TargetSite"] = ex.TargetSite;
eventInfo.Exception = ex;
logger.Log(eventInfo);
}
Any help much appreciated! Thankyou!
Do you run your application with enough rights to write a log file in the root of your C-drive? Try it with ${basedir}/nLogFile.txt and just see if this works.
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
var configuration = new NLog.Config.LoggingConfiguration();
var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "logfile.txt" };
var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
configuration.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, logfile);
configuration.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, logconsole);
NLog.LogManager.Configuration = configuration;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With