ASP.NET Core使用NLog记录日志

时间:2023-03-09 05:55:55
ASP.NET Core使用NLog记录日志

1、根目录新建nlog.config配置文件

<?xml version="1.0"?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="Warn"
internalLogFile="${basedir}\logs\internal-nlog.txt"> <extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions> <targets>
<target name="allfile" xsi:type="File"
fileName="${basedir}\logs\GDStationaryNetCore\${shortdate}.log"
encoding="utf-8"
layout="[${longdate}][${machinename}][${level}] ${message} ${exception}" />
</targets>
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" /> <!--Skip Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>

2、添加NLog包

Install-Package NLog.Web.AspNetCore

3、Configure配置

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} //
env.ConfigureNLog("nlog.config");
//安装System.Text.Encoding.CodePages
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
//add NLog to ASP.NET Core
loggerFactory.AddNLog();
//add NLog.Web
// 修改为 CreateWebHostBuilder(args).UseNLog().Build().Run();
//app.AddNLogWeb(); app.UseMvc();
}

Main方法里配置使用

 public static void Main(string[] args)
{
CreateWebHostBuilder(args).UseNLog().Build().Run();
}

4、使用

public class ValuesController : ControllerBase
{
private readonly ILogger<ValuesController> _logger; public ValuesController(ILogger<ValuesController> logger = null)
{
if (null != logger)
{
_logger = logger;
}
} // GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
_logger.LogInformation($"测试一条日志.");
return new string[] { "value1", "value2" };
} }