简体   繁体   English

如何将值注入NLog.config?

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

I use a NLog.config, but some values I want to change from outside. 我使用NLog.config,但有些值我想从外部更改。 Eg target:adress could change so I want to set it each time the software starts. 例如target:地址可能会更改,因此我想在每次软件启动时进行设置。

I imagine some thing like 我想像

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

How can I set values to my NLog.config? 如何为NLog.config设置值?

You could edit the config in C# like this: 您可以像这样在C#中编辑配置:

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

Please note that combining the config file (nlog.config) and changing it in code, the reload of nlog.config could undo your changes. 请注意,结合配置文件(nlog.config)并在代码中对其进行更改,重新加载nlog.config可能会撤消您的更改。 If you combine both, then reapply the changes on the reload event. 如果您将两者结合使用,则对reload事件重新应用更改。 Eg 例如

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();
};

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

I recommend that one makes use of the NLog context layoutrenderers instead of modifying target properties at runtime. 我建议您使用NLog上下文布局渲染器,而不是在运行时修改目标属性。 It ofcourse requires that the target-property supports NLog Layout. 当然,它要求目标属性支持NLog布局。

Example of NLog.config: NLog.config的示例:

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

Then at runtime you can change the GDC-variables: 然后在运行时,您可以更改GDC变量:

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

${gdc} Can also be combined with WhenEmpty , so one can provide a fallback default value, when nothing has been asigned from code. ${gdc}也可以与WhenEmpty结合使用,这样当代码没有分配任何东西时,它可以提供一个后备默认值。

See also: https://github.com/NLog/NLog/wiki/LogEvent-Context-Information 另请参阅: https : //github.com/NLog/NLog/wiki/LogEvent-Context-Information

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

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