NLog: transition from nlog.config to software configuration

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;

        // 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 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!

+4
1

C-? ${basedir}/nLogFile.txt , .

+4

Source: https://habr.com/ru/post/1543478/


All Articles