c# - ASP.NET-Core 应用程序根目录中的 NLog 日志文件
问题描述
我的 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
将在应用程序根文件夹中创建一个新文件夹,并在文件logs
夹中创建名称为 {shortdate} 的日志文件。
我希望这可以帮助您解决问题。
推荐阅读
- c# - NLog 结构化日志记录将所有值转换为字符串
- php - 在 Laravel 中下载多个上传的文件
- javascript - 如何遍历可观察对象内的列表?
- unit-testing - Vue JS - 单元测试 - 未定义本地存储
- android - 如何使用 Youtube player API 同时播放 2 个 youtube 视频?
- javascript - 在javascript中解码url字符串给出空字符串
- python - 如何获取http请求的状态码?
- php - 将 php 包含在 html 中,首先在网站的错误位置加载
- laravel - laravel Asset() 函数在部署后崩溃
- javascript - Prettier 不在 vscode 上格式化角模板