dotnet6 nlog依赖注入和数据库写入

aspnetcore6,自身携带的四种Logging providers:Console/Debug/EventSource/EventLog (Windows only)
功能有限(参考 https://learn.microsoft.com/zh-cn/aspnet/core/fundamentals/logging/?view=aspnetcore-6.0 ),不包括用于将日志写入文件或者数据库的日志记录提供程序。 若要将日志从 ASP.NET Core 应用写入文件和数据库,只能使用专业性更强的第三方logging provider,例如NLog(https://nlog-project.org/)

通过Microsoft.Extensions.Logging使用NLog步骤:

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(写入到sqlserver数据库):  https://www.nuget.org/packages/NLog.Database/5.0.4

2,配置appsettings.json

参考 https://github.com/NLog/NLog.Extensions.Logging/wiki/NLog-configuration-with-appsettings.json
注意要引入扩展
"extensions": [
{ "assembly": "NLog.Extensions.Logging" },
{ "assembly": "NLog.Web.AspNetCore" },
{ "assembly": "NLog.Database" }
],
另外注意数据库target配置节,dbProvider这里使用最新的Microsoft.Data.SqlClient(ADO.NET driver for SQL Server)替换System.Data.SqlClient

如果使用nlog.config(xml格式),nlog5.0版本不再自动加载nlog扩展(Nlog.Database等),需要配置autoloadExtensions=“true”

<nlog autoloadExtensions="true"> </nlog>
或者引入具体扩展
<nlog> <extensions> <add assembly="NLog.Database" /> </extensions> </nlog>

3,Program.cs添加依赖注入

builder.Host.UseNLog();

点击查看代码
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();
    }
}

比较 NLog GetCurrentClassLogger 和 Microsoft ILogger

https://github.com/NLog/NLog.Extensions.Logging/wiki/NLog-GetCurrentClassLogger-and-Microsoft-ILogger

直接使用 NLog 的优点

最佳性能
记录器 API 的更多选项,例如Logger.WithProperty(..)
适用于所有平台
无需依赖注入,从而节省了复杂性。

通过Microsoft.Extensions.Logging使用NLog的优点:

与 ASP.NET Core完全集成,例如Microsoft还写入记录器API,并且NLog也将捕获(并可能过滤)
写入日志记录抽象将使代码日志库独立。
与 .NET Core 依赖项注入配合良好
从appsettings.json加载NLog配置,而不是使用XML文件NLog.config。

posted @ 2022-11-08 02:14  悠哉大斌  阅读(1263)  评论(0编辑  收藏  举报