簡體   English   中英

ASP.NET-Core 應用程序根目錄中的 NLog 日志文件

[英]NLog log files in ASP.NET-Core Application Root Directory

我的 nlog.config 文件中有以下內容

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

它正在按預期工作並記錄錯誤。

但是,我擔心的是,當應用程序在線托管時,如何使日志文件夾位於我的應用程序根目錄中,因為我可能沒有按照本地計算機上的方式說明應用程序根目錄的物理路徑。

我嘗試替換以下行如下:

 <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 ,並在日志文件夾中創建名稱為 {shortdate} 的logs文件。

我希望這會幫助您解決問題。

您可以考慮使用這些:

對於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";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM