gpt4 book ai didi

c# - 如何使用设置变量为 NLog 配置 Azure 表连接字符串?

转载 作者:行者123 更新时间:2023-12-02 07:47:08 24 4
gpt4 key购买 nike

我遇到一个问题,我需要使用 Nlog 将日志写入 Azure 表,但连接字符串可能会根据环境(即 Dev/UAT 等)而变化,因此我需要从另一个配置文件中获取它。我的 Nlog“目标”部分当前如下所示:

<targets>
<target xsi:type="File" name="allfile" fileName="${var:configDir}\nlog-all.log"
layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />
<target xsi:type="AzureTableStorage"
connectionString="${var:myNLogConnectionString}"
name="NLogAzureTable"
layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}"
tableName="MyTestLogs"
logTimeStampFormat="O" />
</targets>

我的 Api 如下所示:

ILoggerFactory logger = new LoggerFactory().AddNLog();
var nlogConfigSection = config.Settings.Sections["MyService_NlogSettings"];
LogManager.LoadConfiguration("nlog.config");
LogManager.Configuration = new XmlLoggingConfiguration("nlog.config");

LogManager.Configuration.Variables["configDir"] = nlogConfigSection.Parameters["FileLocation"].Value;
LogManager.Configuration.Variables["myNLogConnectionString"] = nlogConfigSection.Parameters["environmentNLogConnectionString"].Value;

从调试中我可以看到 config.settings 值都已按要求检索,甚至配置中的变量都已正确填充。我发现,如果我在本地写入“allfile”文本文件,它会设法检索并填充“configDir”,因为那是文本文件出现的位置!但是,如果我切换到使用 Azure,我可以看到如前所述,该变量正在配置中设置,但是当我查看 Nlog 内部日志文件时,我可以看到它认为连接字符串为空。

有什么明显的地方表明我做错了吗?!?我见过类似问题的解决方案,但它们似乎总是涉及做我已经做过的事情,但我没有得到任何快乐!

最佳答案

尝试这样做:

ILoggerFactory logger = new LoggerFactory().AddNLog();
var nlogConfigSection = config.Settings.Sections["MyService_NlogSettings"];

// Configure global settings before loading NLog.config
NLog.GlobalDiagnosticsContext.Set("configDir", nlogConfigSection.Parameters["FileLocation"].Value);
NLog.GlobalDiagnosticsContext.Set("myNLogConnectionString", nlogConfigSection.Parameters["environmentNLogConnectionString"].Value);

NLog.LogManager.Configuration = new XmlLoggingConfiguration("nlog.config");

使用以下 NLog.config,将 ${var 替换为 ${gdc:

<targets>
<target xsi:type="File" name="allfile" fileName="${var:configDir}\nlog-all.log"
layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />
<target xsi:type="AzureTableStorage"
connectionString="${gdc:myNLogConnectionString}"
name="NLogAzureTable"
layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}"
tableName="MyTestLogs"
logTimeStampFormat="O" />
</targets>

关于c# - 如何使用设置变量为 NLog 配置 Azure 表连接字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54556539/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com