C#-NLog.config在启动时以编程方式设置'archiveEvery'值

问题描述 投票:0回答:1

我有一个具有以下目标的NLog.config文件:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
  autoReload="true"
  throwExceptions="true"
  internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log" >

<variable name="ProgramDataPath"

<target name="MyLog" xsi:type="File" fileName="${ProgramDataPath}/MyLog.txt"
       archiveFileName="${ProgramDataPath}/Archive/Mine/{#}_MyLog.txt" archiveNumbering="Date" archiveEvery="Day" archiveDateFormat="dd-MM-yyyy" maxArchiveFiles="7" />

我希望能够在每次启动我的应用程序时通过将'archiveEvery'属性设置为'Day'或'Month'值来进行修改,这应该通过读取另一个配置文件来完成,属性:

<IsMylogDailyArchiveEnabled>false</IsMylogDailyArchiveEnabled>

False表示应该每月记录一次,True-每天。

到目前为止,我仍然可以阅读后面的内容,但是启动我的应用程序后,NLog.config中的内容似乎没有任何变化。

public string IsMylogDailyArchiveEnabled
{
        get { return _isMylogDailyArchiveEnabled ; }
        set 
        { 
            _isMylogDailyArchiveEnabled = value;

            //Here I can see that 'false' is being returned as it should
            EnableMyLogDailyArchiving(_isMylogDailyArchiveEnabled );
        }
}

private void EnableMyLogDailyArchiving(string value)
    {            
            var config = new XmlLoggingConfiguration("NLog.config");
            var target = config.FindTargetByName("MyLog") as FileTarget;

            if (value == "false")
            {
                //Does not work
                target.ArchiveEvery = FileArchivePeriod.Month;
            }

            else
            {
                target.ArchiveEvery = FileArchivePeriod.Day;
            }            

            //LogManager.ReconfigExistingLoggers();
            LogManager.Configuration = config;                   
    }

尝试过两个选项'LogManager.ReconfigExistingLoggers()'和重新分配配置(请参见上文),但是如上所述,我看不到NLog.config文件内部的任何更改。

任何想法或想法?谢谢

c# logging configuration nlog
1个回答
0
投票

它应该起作用,

LogManager.Configuration = config;时,将重新加载配置并初始化所有目标。因此,将使用新的ArchiveEvery设置。

但是请注意,自动重装已启用(autoReload="true"),因此XML配置中的每个更改都会还原代码中所做的更改。如果您不想这样做,请订阅 LogManager.ConfigurationReloaded

来更改配置

PS:建议在生产中禁用 LogManager.ConfigurationReloaded(例如,通过删除throwExceptions

© www.soinside.com 2019 - 2024. All rights reserved.