Thursday 11 August 2011

Use and transform NLog config in web.config

Ever wonder how to integrate your log platform configuration into your web.config so it can be transformed nicely into different environments, such as QA, staging and production environment? Below is a example config that I worked on for a public transit website.


The original web.config looks like
 
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <targets>
      <target xsi:type="File"
              name="FileLog"
              layout="${longdate} | ${level:uppercase=true} | ${logger} | ${message}"
              fileName="c:\logs\log_${shortdate}.log"/>
    <rules>
      <logger name="*" minlevel="Trace" writeTo="FileLog" />
    </rules>
  </nlog>
 

Your Release.config, for example, will set to below if the production has different path for log files.

 
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"
  xmlns:nlg="http://www.nlog-project.org/schemas/NLog.xsd">

...

<nlg:nlog  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <nlg:targets >
      <nlg:target xsi:type="File"
              name="FileLog"
              layout="${longdate} | ${level:uppercase=true} | ${logger} | ${message}"
              fileName="d:\logs\prod\Log_${shortdate}.log"  xdt:Transform="SetAttributes"  xdt:Locator="Match(name)" />
    </nlg:targets>
  </nlg:nlog>
</configuration>
 

2 comments:

  1. This is even better than NLog:
    http://www.kellermansoftware.com/p-14-net-logging-library.aspx

    ReplyDelete
  2. I'm interested in your solution - I've been fighting this for a while. I'm having problems understanding what you've done though. What does the preceding "nlg:" accomplish in the transform? I know there's issues with Nlog's custom namespace - is this somehow a fix?

    ReplyDelete