gpt4 book ai didi

c# - 在 ASP.NET Core 应用程序中使用 NLog

转载 作者:行者123 更新时间:2023-12-01 22:37:46 26 4
gpt4 key购买 nike

我找到了CodeProject有一个如何让它工作的例子,但它不起作用。主要问题似乎是 Nuget 中似乎不存在 "Microsoft.Framework.Logging.NLog": "1.0.0-*" 包。我看过this StackOverflow question并查看了它引用的 GitHub 示例,但它似乎包含相同的问题。

我尝试让它自己工作,我想出的最好的方法如下:

public class NLogLogger : ILogger
{
public NLogLogger()
{
new WebLoggerConfigurer().ConfigureDefault();
}

public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func<object, Exception, string> formatter)
{
// currently need the global:: for LogLevels because our namespace contains NLog in it. Is there a better naming convention we could use instead?
var ll = logLevel == LogLevel.Debug ? global::NLog.LogLevel.Debug
: logLevel == LogLevel.Verbose ? global::NLog.LogLevel.Trace
: logLevel == LogLevel.Critical ? global::NLog.LogLevel.Fatal
: logLevel == LogLevel.Error ? global::NLog.LogLevel.Error
: logLevel == LogLevel.Information ? global::NLog.LogLevel.Info
: logLevel == LogLevel.Warning ? global::NLog.LogLevel.Warn
: global::NLog.LogLevel.Off;

LogManager.GetCurrentClassLogger().Log(ll, formatter(state, exception));
}

public bool IsEnabled(LogLevel logLevel)
{
return true;
}

public IDisposable BeginScopeImpl(object state)
{
return new Disposable(() => { });
}
}

public class NLogLoggerProvider : ILoggerProvider
{
public void Dispose()
{
}

public ILogger CreateLogger(string categoryName)
{
return new NLogLogger();
}
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddProvider(new NLogLoggerProvider());
..
}

BeginScopeImpl 的实现似乎是一个 hack,但我不确定如何最好地实现它。

  1. 这看起来是一个有效的实现选项吗?
  2. 是否有更好的方法来实现 BeginScopeImpl?
  3. 还有其他方法让 NLog 与 ASP.NET Core 配合使用吗?

最佳答案

对于 ASP.NET Core,您需要 NLog.Web.AspNetCore - 这依赖于 NLog.Extensions.Logging .

注意:Microsoft.Framework.Logging.NLog 已替换为 NLog.Extensions.Logging on NuGet ,由 NLog 团队维护。

使用方法:

设置

需要启用 NLog,以便将其集成到 ASP.NET Core 的 DI 和日志 API 中。这将导致外部(例如 Microsoft)写入的所有日志也将发送到 NLog - 您可以在 NLog 的配置中过滤掉它(不会影响性能)。

ASP.NET Core 1

在 ASP.NET Core 中的 Configure 和可选的 ConfigureServices 需要更新。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//add NLog to .NET Core
loggerFactory.AddNLog();

//Enable ASP.NET Core features (NLog.web) - only needed for ASP.NET Core users
app.AddNLogWeb();

//configure nlog.config in your project root.
env.ConfigureNLog("nlog.config");
...
//you could use LogManager.Configuration from here


public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
// e.g. services.AddMvc();

//needed for NLog.Web
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}

ASP.NET Core 2

对于 ASP.NET Core 2,设置与 ASP.NET Core 1 不同

在program.cs中设置NLog:

using NLog.Web;
using Microsoft.Extensions.Logging;

public static void Main(string[] args)
{
// NLog: setup the logger first to catch all errors
var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try
{
logger.Debug("init main");
CreateWebHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
//NLog: catch setup errors
logger.Error(ex, "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();
}
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
})
.UseNLog(); // NLog: setup NLog for Dependency injection

ASP.NET Core 3 和 5

与 ASP.NET Core 2 相比,有一些小的变化,例如有一个 IHostBuilder 而不是 IWebHostBuilder

对于 ASP.NET Core 5,步骤是相同的​​。

在program.cs中设置NLog:

using System;
using NLog.Web;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Hosting;

public static void Main(string[] args)
{
var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try
{
logger.Debug("init main");
CreateHostBuilder(args).Build().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();
}
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
})
.UseNLog(); // NLog: Setup NLog for Dependency injection

ASP.NET Core 6

对于 ASP.NET Core 6,您可以在没有 Startup 类的情况下配置它。更新 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.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
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();
}

写入日志

使用类类型作为通用参数注入(inject) ILogger

public class HomeController : Controller
{
public HomeController(ILogger<HomeController> logger)
{
logger.LogInformation("created homeController");
}

配置NLog规则

有关如何配置、记录和过滤的示例。

创建一个 nlog.config(有关 nlog.config 的更多信息,请参阅 docs)。

此示例将创建 2 个文件,一个包含所有日志(包括 Microsoft 的日志),另一个文件仅包含您的日志。

<?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="Warn"
internalLogFile="c:\temp\internal.txt">


<extensions>
<!--enable NLog.Web for ASP.NET Core-->
<add assembly="NLog.Web.AspNetCore"/>
</extensions>

<!-- define various log targets -->
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log"
layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />

<target xsi:type="File" name="ownFile" fileName="c:\temp\nlog-own-${shortdate}.log"
layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />

</targets>

<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />

<!--Skip Microsoft logs - no writeTo attribute-->
<logger name="Microsoft.*" minlevel="Trace" final="true" />
<logger name="*" minlevel="Trace" writeTo="ownFile" />
</rules>
</nlog>

发布nlog.config

这不是 ASP.NET Core 5 必需的步骤

确保 nlog.config 将被发布,例如在您的 csproj 文件中:

<ItemGroup>
<Content Update="nlog.config" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

输出

“nlog-own-2018-02-14.log”包含:

2018-02-14 16:27:04.0547|aspnetCoreApplication.Controllers|INFO|created homeController

2018-02-14 16:27:04.0547|aspnetCoreApplication.Controllers|INFO|created homeController

疑难解答

ASP.NET Core 2 中缺少调试日志消息?虽然我们在program.cs中使用SetMinimumLevel,但appsettings.json也可以对此进行融合。

您可以按如下方式更改:

更改appsettings.json:

{
"Logging": {
"LogLevel": {
"Default": "Trace"
}
}
}

您还可以在此处过滤 Microsoft 的日志,例如

{
"Logging": {
"LogLevel": {
"Default": "Trace",
"Microsoft": "Information"
}
}
}

其他问题,请参见此步骤计划查找原因: Logging-troubleshooting in NLog

干杯,

朱利安(NLog)

编辑:针对 NLog.Web.AspNetCore 4.3 进行了更新

编辑 2:更新了 ASP.NET Core 2 和最新建议

编辑 3:针对 ASP.NET Core 3 进行了更新

编辑 4:针对 ASP.NET Core 5 进行了更新

编辑 5:针对 ASP.NET Core 6 进行了更新

关于c# - 在 ASP.NET Core 应用程序中使用 NLog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34679727/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com