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">
	<!-- enable asp.net core layout renderers -->
	<extensions>
		<add assembly="NLog.Web.AspNetCore"/>
	</extensions>
	<!-- the targets to write to -->
	<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 to map from logger name to target -->
	<rules>
		<logger name="testjson.*" minlevel="Trace" writeTo="jsonFile" />
	</rules>
</nlog>

第三步、修改Program.cs

using NLog.Web; //引入
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();
builder.Logging.ClearProviders();//添加
builder.Host.UseNLog();//添加
var app = builder.Build();
// Configure the HTTP request pipeline.
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" };
       
粉丝