Dotnet 框架 - 在 TFS cd 管道中使用变量替换更改 Nlog 配置

Dotnet framework - Nlog configuration change using variable substitution in TFS cd pipeline

我在 web 配置文件中有 Nlog 配置,我想更改 CD 管道中的文件路径,以便根据环境放置一些动态路径。

目前 web.config 文件变量替换(XML 变量替换选项)不支持它。

还有哪些其他方法可以做到这一点?我真的没有选择去 Web.Config 转换方法。

关于这方面的任何指导都会很有帮助。

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  autoReload="true"
  throwExceptions="false"
  internalLogLevel="Error" internalLogFile="c:\Logs\nlog-internal.log">
    <targets name="nlogconfig" async="true">
      <target xsi:type="File" name="name"
         fileName="Path/${shortdate}.log"
         archiveFileName="Path/${shortdate}.{###}.log"
         layout="${longdate} ${uppercase:${level}} ${callsite:className=true:includeSourcePath=true:methodName=true:skipFrames=1:cleanNamesOfAnonymousDelegates=true} ${newline} ${message} ${newline} ${exception:innerFormat=ToString:maxInnerExceptionLevel=2:innerExceptionSeparator=newline:separator=newline:format=ToString,StackTrace}${newline}"
         archiveAboveSize="8388608"
         archiveNumbering="Rolling"
         archiveEvery="Day"
         concurrentWrites="true"
         maxArchiveFiles="100" />
    </targets>
    <rules>
      <logger name="*" minlevel="Debug" writeTo="name" />
    </rules>
  </nlog>

What are the other ways this can be done?

您可以使用 Replace Tokens Extension 中的 替换令牌任务

这是我的步骤,你可以参考一下:

Nlog 配置:

<targets>
    <target name="logfile" xsi:type="File" fileName="#{variable}#/#{shortdate}#.log />
    <target name="logconsole" xsi:type="Console" />
</targets>

替换令牌任务示例:

- task: replacetokens@3
  inputs:
    rootDirectory: 'Folder Path'
    targetFiles: '**/*.config'
    encoding: 'auto'
    writeBOM: true
    actionOnMissing: 'warn'
    keepToken: false
    tokenPrefix: '#{'
    tokenSuffix: '}#'
    useLegacyPattern: false
    enableTelemetry: true

变量:

然后Nlog配置中的变量将被替换。

替代解决方案是在默认 NLog.config 旁边部署一个 environment-specific override-file。

environment-specificNLog.override.config的例子:

    <nlog>
        <variable name="LogDirectory" value="D:/Path" />
    </nlog>

NLog.config 示例:

    <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    
      <variable name="LogDirectory" value="${basedir}" /> <!-- Default Value -->
    
      <include file="NLog.override.config" ignoreErrors="true" /> <!-- Override Value -->
    
      <targets async="true">
          <target xsi:type="File" name="name" fileName="${LogDirectory}/${shortdate}.log" />
      </targets>
      <rules>
          <logger name="*" minlevel="Debug" writeTo="name" />
      </rules>
    </nlog>

deployment-package 可以包含多个 nlog.override.config 文件。每个环境一个,然后根据所选环境部署正确的一个。

另请参阅:https://github.com/nlog/nlog/wiki/Configuration-file#include-files