gpt4 book ai didi

c# - 在 asp.net core 2.0 web 应用程序中使用 NLog

转载 作者:太空狗 更新时间:2023-10-29 19:38:27 26 4
gpt4 key购买 nike

在 asp.net core 2.0 web 应用程序中使用 Nlog 的最佳方式是什么

我发现了很多不同的解决方案如何配置。这是其中的两个。还有其他更好的方法吗?

A) 在启动服务器之前创建记录器:

 public class Program
{
public static void Main(string[] args)
{
// NLog: setup the logger first to catch all errors
var logger = NLogBuilder.ConfigureNLog("NLog.config").GetCurrentClassLogger();
try
{
logger.Debug("init main");
BuildWebHost(args).Run();
}
catch (Exception e)
{
//NLog: catch setup errors
logger.Error(e, "Stopped program because of exception");
throw;
}
}

public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>().UseNLog() // use NLog for DI Logger
.Build();
}

B) 配置内部启动

public class Startup
{
public Startup(IHostingEnvironment env, IConfiguration configuration)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddNLog();
loggerFactory.ConfigureNLog("nlog.config");

LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("myDb");

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseMvc();
}
}

最佳答案

关于这个有一个 wiki 文档:

https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2

要注入(inject)连接字符串等自定义数据,只需创建并注册一个自定义布局渲染器即可:

https://github.com/NLog/NLog/wiki/How-to-write-a-custom-layout-renderer

或者在启动时将连接字符串放入 NLog-Global-Diagnostic-Context 中:

https://github.com/NLog/NLog/wiki/Var-Layout-Renderer

也许是这样的,其中 NLog.config 使用了 ${gdc:connectionString}:

var myConnectionString = Configuration.GetConnectionString("myDb");
NLog.GlobalDiagnosticsContext.Set("connectionString", myConnectionString);
var logFactory = NLogBuilder.ConfigureNLog("NLog.config"); // Uses ${gdc:connectionString}
var logger = logFactory.GetCurrentClassLogger();
logger.Info("Hello World");

另见 https://github.com/NLog/NLog/wiki/Gdc-Layout-Renderer

更新 - ${configsetting}

NLog.Extension.Logging 版本。 1.4 现在支持 ${configsetting} 因此 NLog 可以直接从 appsettings.json 读取设置而不需要使用 NLog 变量。参见 https://github.com/NLog/NLog/wiki/ConfigSetting-Layout-Renderer

关于c# - 在 asp.net core 2.0 web 应用程序中使用 NLog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47413473/

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