aspnetcore6,自身携带的四种Logging providers:Console/Debug/EventSource/EventLog (Windows only)
Logging providers - .NET | Microsoft Learn
功能有限,使用专业性更强的第三方logging provider,例如NLog(https://nlog-project.org/)
步骤:
1,创建aspnetcore6 web项目(带控制的webapi或者mvc)后,首先安装 4个依赖包
NLog: https://www.nuget.org/packages/NLog/5.0.4
NLog.Web.AspNetCore: https://www.nuget.org/packages/NLog.Web.AspNetCore/5.1.0
NLog.Extensions.Logging: https://www.nuget.org/packages/NLog.Extensions.Logging/5.0.1
NLog.Database(写入到数据库): https://www.nuget.org/packages/NLog.Database/5.0.4
2,配置appsettings.json (NLog configuration with appsettings.json · NLog/NLog.Extensions.Logging Wiki (github.com))
如果使用nlog.config,nlog5.0版本不再自动加载nlog扩展(Nlog.Database等),需要配置autoloadExtensions=“true”
<nlog autoloadExtensions="true">
</nlog>
3,Program.cs添加依赖注入
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.AddControllersWithViews(); // NLog: Setup NLog for Dependency injection builder.Logging.ClearProviders(); builder.Host.UseNLog(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); 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(); }
4,注入到控制器
using Microsoft.Extensions.Logging; public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; _logger.LogDebug(1, "NLog injected into HomeController"); } public IActionResult Index() { _logger.LogInformation("Hello, this is the index!"); return View(); } }
标签:Logging,app,dotnet6,写入,NLog,https,org,nlog,logger From: https://www.cnblogs.com/imust2008/p/16868012.html