作为计划任务运行时,NLog环境布局渲染器不起作用

我在Windows Server 2012上使用NLog 4.4.12和.NET 4.6.2。

我已经configuration了我的app.config与nlog部分,如下所示:

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <include file="conf/nlog.${environment:MY_ENV}.config"/> </nlog> 

这里的想法是,它会引入一个环境特定的configuration来设置NLog。

我设置了一个称为MY_ENV的系统环境variables(不是用户),并将其值设置为production

如果我以当前login的用户身份运行该程序,则find正确的configuration文件,并按预期写入日志。

但是,如果我通过Windows任务计划程序设置计划任务,以使用刚才使用的相同用户凭据来运行程序,那么似乎找不到环境variables?

我configuration了计划的任务以运行用户是否login ,并且已经启用了运行最高权限

当启用NLog的内部诊断时,我在诊断日志中看到以下内容:

 2017-10-19 19:27:42.1744 Error Error when including 'conf/nlog..config'. Exception: System.IO.FileNotFoundException: Included file not found: E:\Utilities\MyApp\conf/nlog..config at NLog.Config.XmlLoggingConfiguration.ParseIncludeElement(NLogXmlElement includeElement, String baseDirectory, Boolean autoReloadDefault) 2017-10-19 19:27:42.1744 Error Parsing configuration from E:\Utilities\MyApp\MyApp.exe.Config failed. Exception: NLog.NLogConfigurationException: Exception when parsing E:\Utilities\MyApp\MyApp.exe.Config. ---> NLog.NLogConfigurationException: Error when including: conf/nlog..config ---> System.IO.FileNotFoundException: Included file not found: E:\Utilities\MyApp\conf/nlog..config at NLog.Config.XmlLoggingConfiguration.ParseIncludeElement(NLogXmlElement includeElement, String baseDirectory, Boolean autoReloadDefault) --- End of inner exception stack trace --- at NLog.Config.XmlLoggingConfiguration.ParseIncludeElement(NLogXmlElement includeElement, String baseDirectory, Boolean autoReloadDefault) at NLog.Config.XmlLoggingConfiguration.ParseNLogElement(NLogXmlElement nlogElement, String filePath, Boolean autoReloadDefault) at NLog.Config.XmlLoggingConfiguration.ParseTopLevel(NLogXmlElement content, String filePath, Boolean autoReloadDefault) at NLog.Config.XmlLoggingConfiguration.Initialize(XmlReader reader, String fileName, Boolean ignoreErrors) --- End of inner exception stack trace --- 

正如你所看到的,它似乎得到一个空string或空值的包含文件的path的布局呈现。 这导致文件path呈现为: conf/nlog..config

我不确定这是NLog的具体问题。 我查看了Environment Layout Renderer的源代码,并最终调用了Environment.GetEnvironmentVariable(string) 。

我觉得这可能与Windows中计划任务的性质有关,但是我不确定我的select是什么。

无论用户是否login,该任务都需要自动运行。

有人能解释这里发生了什么吗? 为什么NLog无法拉入正确的环境variables? 我能做些什么来解决这个问题?

我认为这是问题,更改环境变量时,您需要重新启动Taskeng.exe。

您应该终止Taskeng.exe,下一次计划的任务运行将得到一个更新的环境。

https://superuser.com/questions/331077/accessing-environment-variables-in-a-scheduled-task