前言
之前的这篇文章中介绍了,桌面程序是如何使用Nlog的
但是如果是WebApi,有一点不同,总的来说,前期的配置工作变多了。其他的不变。
安装
首先是安装包:建议5以上版本
nlog.config
然后准备一个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"
autoReload="true"
throwExceptions="true"
internalLogLevel="Off"
internalLogFile="Logs\internal-nlog-AspNetCore.txt">
<targets>
<!--控制台输出-->
<target name="console" xsi:type="ColoredConsole" layout="${date:format=HH\:MM\:ss} ${logger} ${message}"/>
<!--调试输出,带行号-->
<target name="debug_file"
xsi:type="File"
fileName="${basedir}/Logs/${shortdate}/Debug/log.txt"
maxArchiveFiles="30"
layout="【${longdate}】${level:uppercase=false} ${callsite:className=True:fileName=True:includeSourcePath=False:methodName=False}:${message}" />
<!--错误输出,带行号-->
<target name="error_file"
xsi:type="File"
fileName="${basedir}/Logs/${shortdate}/log.txt"
maxArchiveFiles="30"
layout="【${longdate}】${level:uppercase=false} ${callsite:className=True:fileName=True:includeSourcePath=False:methodName=False}:${message}" />
</targets>
<rules>
<logger name="System.*" finalMinLevel="Warn"/>
<logger name="Microsoft.*" finalMinLevel="Warn"/>
<logger name="Microsoft.Hosting.Lifetime*" finalMinLevel="Info"/>
<logger name="*" minlevel="Trace" writeTo="console" />
<logger name="*" minlevel="Debug" writeTo="debug_file" />
<logger name="*" minlevel="Error" writeTo="error_file" />
</rules>
</nlog>
对Config的简单说明
autoReload="true"
在配置文件头部的这个属性,如果有True,在网站跑的过程中,可以随时变更nlog.config文件,随时生效。
throwExceptions="true"
这个前期对nlog.config文件如果有写法错误,或是项目中对日志模块有什么异常错误的话,会主动抛出来,这个对前期集成NLog模块或写配置文件时有用。
<logger name="System.*" finalMinLevel="Warn"/> <logger name="Microsoft.*" finalMinLevel="Warn"/> <logger name="Microsoft.Hosting.Lifetime*" finalMinLevel="Info"/>
这个主要是过滤掉一些WebApi内部的一些打印信息,不然你的打印会带出来其他的一堆打印。但是程序启动的WebApi的一些内容,目前我发现过滤不掉。不过之后就没有了。
修改Program.cs
最关键的一句话
builder.Logging.AddNLog("nlog.config");
Program.cs中加入这句
这就相当于注册,为注入做准备,不然控制器里的_logger也无法输出log到文件
注入之后,控制器里直接用就好了:
控制器使用情况
Program.cs的全部内容如下:
using MySocketLib.TcpSvr;
using NLog;
using NLog.Web;
var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
logger.Debug("init main");
try
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//为了返回任意形式xml,需要这个,需要安装包:Microsoft.AspNetCore.Mvc.WebApiCompatShim
builder.Services.AddMvc().AddWebApiConventions();
builder.Logging.AddNLog("nlog.config");
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
//启动TCP
TcpSvrCtrl.Run();
app.Run();
}
catch (Exception exception)
{
// NLog: catch setup errors
logger.Error(exception, "Stopped program because of exception");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
NLog.LogManager.Shutdown();
}