Skip to content

WebService target Workaround for url variables

Rolf Kristensen edited this page Nov 27, 2021 · 7 revisions

⚠️ NLog 5.0 now supports Layout for the Url-parameter, so this work-around is no longer needed.

Given config

*a target configured as in: https://github.com/NLog/NLog/wiki/Webservice-Target-for-Splunk

Workaround

Tool driven

Manual

  • Create a Nlog.Release.config (XML-File) to override the hard coded url
    • The name must be same as the name from your original target!
  • Install Package "Microsoft.VisualStudio.SlowCheetah"
  • Update your csproj file:
<ItemGroup>
       <Content Update="Nlog.config">
           <CopyToOutputDirectory>Always</CopyToOutputDirectory>
           <TransformOnBuild>true</TransformOnBuild>
       </Content>
       <None Include="Nlog.Release.config">
           <IsTransformFile>true</IsTransformFile>
           <DependentUpon>Nlog.config</DependentUpon>
       </None>
   </ItemGroup>

Content of nlog.Release.config

<?xml version="1.0" encoding="utf-8"?>
<!--For more information on using transformations see the web.config examples at http://go.microsoft.com/fwlink/?LinkId=214134. -->
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" internalLogLevel="Information" internalLogFile="c:\temp\internal-nlog.txt" xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
    <targets async="true">
        <target xsi:type="WebService"
         name="Splunk"
         url="NEWURL"
         protocol="JsonPost"
         encoding="utf-8"
         preAuthenticate="true"
                xdt:Transform="SetAttributes(url)" xdt:Locator="Match(name)">
        </target>
    </targets>
</nlog>

If NEWURL is a variable

  • In program.cs modify nlog.config before configuring Nlog
var token = Environment.GetEnvironmentVariable("YOURURL");
     if (!string.IsNullOrWhiteSpace(token))
     {
       var currentFolder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
       var nlogFolder = $"{currentFolder}/nlog.config";
  
       var configText = File.ReadAllText(nlogFolder);
       var updatedConfig = configText
         .Replace("NEWURL", token);
  
       File.WriteAllText(nlogFolder, updatedConfig);
     }
var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
//...
Clone this wiki locally