53

我的 NLog 目标是这样的:

<targets>
  <target xsi:type="Console" name="console" 
    layout="${longdate}|${level}|${message}" />
  <target xsi:type="File" name="ErrorLog" fileName="${basedir}/error.txt"
          layout="${longdate}
          Trace: ${stacktrace} 
          ${message}" />
  <target xsi:type="File" name="AccessLog" fileName="${basedir}/access.txt"
          layout="${shortdate} | ${message}" />
</targets>

但是如果用户不是他们机器上的管理员,这会导致问题,因为他们没有对“程序文件”的写访问权。我怎样才能得到类似%AppData%NLog 而不是 BaseDir 的东西?

4

5 回答 5

92

您正在寻找NLog 特殊文件夹

例子:

...fileName="${specialfolder:folder=ApplicationData}/Program/file.txt"...
于 2010-01-04T15:55:43.747 回答
13

奥伦的答案应该是正确的答案。但是,在我的一生中,我无法让它与使用 nLog 2.0.0.0 的 .NET 4.0 网站一起使用。我最终只使用了

fileName="${basedir}app_data\logs\${shortdate}.log" 
于 2011-03-24T22:50:27.707 回答
7

${specialfolder:ApplicationData} 也可以

于 2011-02-22T06:02:56.077 回答
1

登录到项目目录:

虽然前面的答案适用于原始问题,但搜索如何登录到项目APP_DATA目录会导致这个问题。虽然bkaid的答案适用于 ASP.NET 并APP_DATA专门用于使用文件夹,但对于 .NET Core 和 .NET 5,解决方案有点不同,因为该主题已被放弃,转而wwwroot只为那些应该送达,其余的都是私人的。那么,.NET Core/5 的答案是写入解决方案根目录:

  1. 首先,确保将NLog.Web.AspNetCore程序集添加到nlog.config
    <extensions>
        <add assembly="NLog.Web.AspNetCore"/>
    </extensions>
    
  2. 然后使用该扩展提供的布局渲染器之一,在本例${aspnet-appbasepath}中它引用解决方案根目录:
    <targets>
        <target name="file"
                type="File"
                xsi:type="File"
                fileName="${aspnet-appbasepath}/log/${shortdate}.log"
                layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}"/>
    </targets>
    

这会将文件写入<solution folder>/log/2021-07-01.log,而面向公众的网站将永远不会提供该文件。此程序集提供的其他布局渲染器列在 NLog 网站上

于 2021-07-01T23:14:22.973 回答
1

以前的答案帮助解决了我遇到的问题,但几年后,解决方案现在在 v4.3 下有所不同。目录和文件名与路径组合在一起。

@theGecko 的链接仍然是最新的语法,但该页面缺少示例:

https://github.com/nlog/NLog/wiki/Special-Folder-Layout-Renderer

以下示例将文件写入myLog.log当前用户应用程序数据漫游目录C:\USers\current.user\AppData\Roaming\My\Path\Somewhere

fileName="${specialfolder:dir=My/Path/Somewhere/:file=myFile.log:folder=ApplicationData}"
于 2016-07-08T23:04:35.203 回答