繁体   English   中英

如何将值注入NLog.config?

[英]How to inject values into my NLog.config?

我使用NLog.config,但有些值我想从外部更改。 例如target:地址可能会更改,因此我想在每次软件启动时进行设置。

我想像

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可能会撤消您的更改。 如果您将两者结合使用,则对reload事件重新应用更改。 例如

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/LogEvent-Context-Information

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM