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

时间:2017-10-19 23:49:31

标签: windows nlog taskscheduler

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

我已经使用nlog部分配置了我的app.config,如下所示:

  <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>

这里的想法是它将引入一个特定于环境的配置来设置NLog。

我设置了一个名为MY_ENV的系统环境变量(非用户),并将其值设置为production

如果我以当前登录的用户身份运行该程序,则会找到正确的配置文件,并按预期写入日志。

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

我已将计划任务配置为运行用户是否已登录,并且我已启用以最高权限运行

当我启用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 ---

正如您所看到的,似乎是为包含文件的路径的布局呈现获取空字符串或空值。这会导致文件路径呈现为:conf/nlog..config

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

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

无论用户是否登录,此任务都需要自动运行。

有人可以解释这里发生了什么吗?为什么NLog无法引入适当的环境变量?我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:1)

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

  

您应该终止Taskeng.exe,并且下次运行计划任务时,它将获得更新的环境。

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