安装两个 NuGet 包:Microsoft.Extensions.Logging,Serilog.AspNetCore
如何配置Program.cs,builder 具体如何配置自行解决:
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Host.UseSerilog((context, logger) =>
{logger//set log level to information.MinimumLevel.Information().WriteTo.Console().WriteTo.File(Path.Combine("logs", @"log.txt"), rollingInterval: RollingInterval.Day);
});
然后在 Controller 里面注入日志依赖,完成:
private readonly ILogger<控制器命名> _logger;public 控制器命名(ILogger<控制器命名> logger){this._logger = logger;}[HttpPost]public IActionResult Post(){_logger.LogTrace("日志跟踪");_logger.LogDebug("日志调试");_logger.LogCritical("日志关键");_logger.LogInformation("日志信息");_logger.LogWarning("日志警告");_logger.LogError("日志错误");}