如何将值注入我的 NLog.config?

How to inject values into my NLog.config?

我使用 NLog.config,但我想从外部更改一些值。例如。 target:adress 可能会改变,所以我想在每次软件启动时设置它。

我想像

var logger = new LoggerFactory().AddNLog().CreateLogger<Program>();
logger.target.adress = "myNewAdress";

如何为我的 NLog.config 设置值?

您可以像这样在 C# 中编辑配置:

var configuration = LogManager.Configuration;
var fileTarget = configuration.FindTargetByName<FileTarget>("myTargetName");
fileTarget.FileName = "${basedir}/file.log";
LogManager.Configuration = configuration; //apply

请注意,结合配置文件 (nlog.config) 并在代码中更改它,nlog.config 的重新加载可能会撤消您的更改。如果将两者结合,则重新应用重新加载事件的更改。例如

public void UpdateConfig()
{
    var configuration = LogManager.Configuration;
    var fileTarget = configuration.FindTargetByName<FileTarget>("myTargetName");
    fileTarget.FileName = "${basedir}/file.log";
    LogManager.Configuration = configuration; //apply
}

// On start of your program
UpdateConfig();

LogManager.ConfigurationReloaded += (sender, e) =>
{
    //Re apply if config reloaded
    UpdateConfig();
};

另请参阅:https://github.com/NLog/NLog/wiki/Configure-from-code

我建议使用 NLog 上下文布局渲染器,而不是在运行时修改目标属性。它当然需要目标-属性 支持 NLog 布局。

NLog.config的例子:

<nlog>
    <targets>
       <target type="file" name="file" fileName="${gdc:item=LogDir}\LogFile.txt}" />
    </targets>
    <rules>
       <logger minLevel="Trace" writeTo="file" />
    </rules>
</nlog>

然后在运行时您可以更改 GDC 变量:

NLog.GlobalDiagnosticsContext.Set("LogDir", "C:\Temp");

${gdc} 也可以与 WhenEmpty 结合使用,因此可以在代码中没有指定任何内容时提供备用默认值。

另请参阅:https://github.com/NLog/NLog/wiki/Context