我在 Nlog: 中使用了一个简单的新空项目。
这是 appsettings.json
文件:
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Debug"
}
},
"AllowedHosts": "*"
}
program.cs
文件是:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}).ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Debug);
})
.UseNLog();
在我的控制器中,我做了一个简单的日志操作:
[HttpGet]
public IActionResult Get()
{
_logger.LogDebug("***test***");
return Ok();
}
(此处删除了 nlog.config
文件,因为冗长)。
当我运行一个简单的测试时,我得到了这个:
红色矩形是 Nlog 模板(带有消息)。
但是看看顶部的箭头会发生什么。还有一条记录的消息。
这是因为那一行:
logging.AddConsole();
如果我删除那行,我会得到这个:
这很好,但是然后我没有看到我需要的“启动日志”(url、端口、应用程序启动消息)。
问题:
我怎样才能在记录消息时只去掉红色部分:
答案 0 :(得分:1)
尝试将您的 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"
throwConfigExceptions="true"
internalLogLevel="info"
internalLogFile="logs/internal-nlog.txt">
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<targets>
<target xsi:type="Console" name="lifetimeConsole"
layout="${level:truncate=4:tolower=true}\: ${logger}[0]${newline} ${message}${exception:format=tostring}" />
<target xsi:type="Console" name="Console"
layout="${longdate} ${newline} ▌ ${when:when=length('${aspnet-item:variable:requestId}')>0:Inner=${aspnet-item:variable:requestId}:else=${mdlc:item=requestId} } ${newline} ▌ ${when:when=length('${aspnet-item:variable:phoneCarKey}')>0:Inner=${aspnet-item:variable:phoneCarKey}:else=${mdlc:item=phoneCarKey} } ${newline} ▌ url: ${aspnet-request-url} ${newline} ▌ message: ${message} ${newline} ▌ callsite : ${callsite} ${newline} ▌ ${when:when=length('${exception}')>0:Inner=exception \: }${exception:format=message,type,method,stacktrace}" />
</targets>
<rules>
<!--Output hosting lifetime messages to make Docker / Visual Studio happy -->
<logger name="Microsoft.Hosting.Lifetime" level="Info" writeTo="lifetimeConsole" final="true" />
<!--Skip Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" maxlevel="Info" final="true" />
<logger name="*" minlevel="Debug" writeTo="Console" />
</rules>
</nlog>
为 Microsoft.Hosting.Lifetime 添加了额外的 LoggingRule,因此您可以获得所需的启动日志。
另见:https://github.com/NLog/NLog.Web/wiki/Hosting-Lifetime-Startup-Messages