问题描述
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<!-- optional,add some variables
https://github.com/nlog/NLog/wiki/Configuration-file#variables
-->
<variable name="basedir" value="c:\Users\user\source\repos\projectname\projectname"/>
<!--
See https://github.com/nlog/nlog/wiki/Configuration-file
for @R_675_4045@ion on customizing logging rules and outputs.
-->
<targets>
<!--
add your targets here
See https://github.com/nlog/NLog/wiki/Targets for possible targets.
See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
-->
<!--write events to a file with the date in the filename.-->
<target xsi:type="file" name="f" filename="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
</targets>
<rules>
<!-- add your logging rules here -->
<!--Write all events with minimal level of Debug (So Debug,Info,Warn,Error and Fatal,but not Trace) to "f"-->
<logger name="*" minlevel="Debug" writeto="f" />
</rules>
</nlog>
,它正在正常工作并记录了预期的错误。
但是,我担心的是,当应用程序在线托管时,如何使logs文件夹位于我的应用程序根目录中,因为我可能没有清楚地知道应用程序根目录的物理路径?本地计算机。
我尝试将以下行替换为以下内容:
<variable name="basedir" value="c:\Users\user\source\repos\projectname\projectname"/>
替换为
<variable name="basedir" value="~/" />
它不起作用。
我也尝试过如下替换以下行
<target xsi:type="file" name="f" filename="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
替换为
<target xsi:type="file" name="f" filename="${Server.MapPath(~)}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
但是它不起作用。
无论应用程序的托管位置如何,请帮助指导我如何将日志文件夹放置在应用程序根目录下。
谢谢
解决方法
如果未为日志文件提供特定路径,则默认情况下,日志记录框架会将日志文件创建到应用程序运行的同一位置。
因此,如果要在应用程序的根文件夹中生成日志文件,则只需提供相对文件路径。
在这种情况下,您需要按以下方式配置文件路径。
internalLogFile="nlog-internal.log"
使用上面的nlog-internal.log
行将在应用程序根文件夹中创建文件。
和
filename="logs/${shortdate}.log"
在上面的行中,将在应用程序根文件夹中创建一个新文件夹logs
,并在logs
文件夹中创建名称为{shortdate}的日志文件。
我希望这可以帮助您解决问题。
,您可以考虑使用这些:
- ${specialfolder:folder=CommonApplicationData}
- ${aspnet-appbasepath}来自NLog.Web.AspNetCore(请记住包括在
<extensions>
中)
对于internalLogFile="..."
,您只能使用以下限制:%appdata%
,${basedir}
,${processdir}
,${currentdir}
,${tempdir}
。
但是您始终可以在运行时分配自己的自定义路径。像这样:
<variable name="LogDirectory" value="${gdc:AppDirectory:whenEmpty=${basedir}}" />
<targets>
<target type="file" filename="${LogDirectory}/Hello.txt" />
</targets>
然后在运行时在应用启动时执行此操作:
NLog.GlobalDiagnosticsContext.Set("AppDirectory",@"C:\Temp\");
NLog.Common.InternalLogger.LogFile = @"C:\Temp\nlog-internal.log";