title: NLog: Switching from nlog.config to programmatic configuration
body: <p>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:</p>
  
  <pre><code>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);      
      }
  </code></pre>
  
  <p>Does anyone know what this isn't working? Heres the documentation I based this off of:
  <a href="https://github.com/nlog/NLog/wiki/Configuration-API" rel="noreferrer">https://github.com/nlog/NLog/wiki/Configuration-API</a></p>
  
  <p>If it helps, here's what I had back when I used the nlog.config file and it worked fine:</p>
  
  <pre><code>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);     
      }
  </code></pre>
  
  <p>Any help much appreciated! Thankyou!</p>