Andrew
Andrew

Reputation: 477

NLog - Variable Update (at runtime)

Trying to update a variable at runtime with NLog on a vb.net (asp.net) application and doesn't appear to be working.

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
  autoReload="true"
  throwExceptions="false"
  internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">


<variable name="DebugInfoLayout" value="[${date:format=MM/dd/yyyy hh\:mm\:ss.fff tt}] [${gdc:item=location}]  |  ${level}  |  ${message}" />
  <variable name="InfoLayout" value="[${date:format=MM/dd/yyyy hh\:mm\:ss.fff tt}] ${gdc:item=SoftwareName} Version ${gdc:item=SoftwareVersion}  -  ${message}" />
  <variable name="LogLayout" value="[${date:format=MM/dd/yyyy hh\:mm\:ss.fff tt}] ${message}" />
  <variable name="logDir" value="C:/Logfiles/" />
  <variable name="ArchiveDir" value="C:/Logfiles/Archive" />
  <variable name="Line" value="" />

  <targets async="false">
    <target name="Errors" xsi:type="File" fileName="${logDir}/${var:Line}errors.log" layout="${DebugInfoLayout}" keepFileOpen="false" archiveFileName="${ArchiveDir}/errors_${shortdate}.{##}.log" archiveNumbering="Sequence" archiveEvery="Day" maxArchiveFiles="30" archiveOldFileOnStartup="true" />
    <target name="Info" xsi:type="File" fileName="${logDir}/${var:Line}info.log" layout="${InfoLayout}"  keepFileOpen="false" archiveFileName="${ArchiveDir}/info_${shortdate}.{##}.log" archiveNumbering="Sequence" archiveEvery="Day" maxArchiveFiles="30"/>
    <target name="Debug" xsi:type="File" fileName="${logDir}/${var:Line}debug.log" layout="${DebugInfoLayout}"  keepFileOpen="false" archiveFileName="${ArchiveDir}/debug_${shortdate}.{##}.log" archiveNumbering="Sequence" archiveEvery="Day" maxArchiveFiles="30" />  
  </targets>

  <rules>
    <logger name="Errors" minlevel="Trace" maxlevel="Fatal" writeTo="Errors" />
    <logger name="Info" minlevel="Trace" maxlevel="Warn" writeTo="Info" />
    <logger name="Debug" minlevel="Trace" maxlevel="Fatal" writeTo="Debug" />
  </rules>

</nlog>

The variable I am trying to update is called "Line" and I have the following code:

NLog.GlobalDiagnosticsContext.Set("Line", "myLine")

However - the log file name is always "debug.log" instead of "myLinedebug.log".

Upvotes: 5

Views: 7041

Answers (1)

Julian
Julian

Reputation: 36790

Instead of

GlobalDiagnosticsContext.Set("Line", "myLine")`

use

LogManager.Configuration.Variables["line"] = "myLine"

Although the GlobalDiagnosticsContext and variables use alike concepts, those are not the same. The GlobalDiagnosticsContext is used for ${gdc} renderer.

See the docs of ${var}

Upvotes: 8

Related Questions