在 NLog 目标中使用 ${basedir} 创建一个具有该名称的文件夹

Using ${basedir} in NLog target creates a folder by that name

我在 Asp.Net 核心 2.0 项目中使用 NLog.Web.AspNetCore。如果我使用以下目标:

<target xsi:type="File" name="allfile" fileName="${basedir}/nlog-all-${shortdate}.log"

它在我的应用程序的 ContentRoot 文件夹中创建了一个名为“${basedir}”的空文件夹。它将日志文件放在 bin\Debug\netcoreapp2.0 中。

为什么它不替代 ${basedir}?如果我使用日志文件夹的完整路径,它工作正常。

我应该补充一点,我在 nlog.config 中的 < nlog > 元素内也有以下内容:

internalLogFile="${basedir}/internal-nlog.txt"

当出现内部 Nlog 错误时,它会写入名为“${basedir}”的文件夹中的此文件。

创建${basedir}文件夹,因为NLog Internal Logger非常原始,不知道layout-renders。

  • 更新 NLog 版本。 4.6 添加了对在 internalLogFile
  • 中使用 ${basedir} 的支持

Asp.Net.Core 的解决方法如下(在 Program.cs 中的 Wiki Example 中添加了两行):

var appBasePath = System.IO.Directory.GetCurrentDirectory();
NLog.GlobalDiagnosticsContext.Set("appbasepath", appBasePath);
var logger = LogManager.LoadConfiguration("nlog.config").GetCurrentClassLogger();

然后您可以在 nlog.config:

中使用 ${gdc:item=appbasepath}
<target xsi:type="File" name="allfile" fileName="${gdc:item=appbasepath}/Logs/nlog-all-${shortdate}.log"

在等待 ${aspnet-appbasepath} 准备就绪时。