【发布时间】:2019-02-06 14:59:31
【问题描述】:
我有一个问题,我需要使用 Nlog 将日志写入 Azure 表,但连接字符串可能会根据环境(即 Dev/UAT 等)而改变,因此我需要从另一个配置文件中获取它。我的 Nlog 'targets' 部分目前如下所示:
<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 内部日志文件时,我可以看到它认为连接字符串是空白的。
有什么明显的地方我做错了吗?!?我已经看到了类似问题的解决方案,但它们似乎总是涉及到我已经做过的事情,但我没有得到任何乐趣!
【问题讨论】:
-
您现在可以使用
${configsetting}直接从appsettings.json 读取:github.com/NLog/NLog/wiki/ConfigSetting-Layout-Renderer -
如果您解释您使用的 NLog 目标可能是个好主意(在您的问题中添加指向 nuget-package 的链接)。也可以在 github 上为目标发布这个问题。
标签: c# .net azure asp.net-core nlog