Previously, in my application ASP.NET MVC5 worked with errors while working with the nlog.config file. Now I want to move away from the approach to the configuration file; I want to programmatically configure Nlog and remove the need for a configuration file. The examples are good when I show how to configure it programmatically, but I am confused about how to actually call the configuration class and actually implement it. Here is what I have:
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
NALSPrincipal userInfo = (NALSPrincipal)Context.User;
var config = new LoggingConfiguration();
var fileTarget = new FileTarget();
config.AddTarget("file", fileTarget);
fileTarget.FileName = "C:/nlogFile.txt";
fileTarget.Layout = "Exception Type: ${exception:format=Type}${newline}
Target Site: ${event-context:TargetSite}${newline}
Message: ${message}";
var rule2 = new LoggingRule("*", LogLevel.Trace, fileTarget);
config.LoggingRules.Add(rule2);
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 this is not working? Here is the documentation on which I based this:
https://github.com/nlog/NLog/wiki/Configuration-API
If this helps, here is what I had 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 is much appreciated! Thankyou!