GitHub地址:
JsonLayout · NLog/NLog Wiki · GitHub
第一步、引入包
<PackageReference Include="NLog" Version="5.0.4" />
<PackageReference Include="NLog.Web.AspNetCore" Version="5.1.4" />
第二步、创建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"
internalLogLevel="Info"
internalLogFile="D:\temp\internal-nlog-AspNetCore.txt">
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<targets>
<target name="jsonFile" xsi:type="File" fileName="log-file.json" >
<layout xsi:type="JsonLayout">
<attribute name="time" layout="${longdate}" />
<attribute name="level" layout="${level:upperCase=true}"/>
<attribute name="message" layout="${message}" />
</layout>
</target>
</targets>
<rules>
<logger name="testjson.*" minlevel="Trace" writeTo="jsonFile" />
</rules>
</nlog>
第三步、修改Program.cs
using NLog.Web;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Logging.ClearProviders();
builder.Host.UseNLog();
var app = builder.Build();
if (app.Environment.IsDevelopment())
app.UseSwagger();
app.UseSwaggerUI();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
第四步、在控制器中使用
using Microsoft.AspNetCore.Mvc;
namespace testjson.Controllers
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
_logger = logger;
[HttpGet]
public IEnumerable<string> Get()
_logger.LogDebug("成功了");
_logger.LogError("看是不是成功了");
return new string[] { "Cool", "Weather" };
粉丝