我一整天都在研究这个问题,并查看了 NLog 文档、StackOverflow 和 NLog GitHub 问题。但是,没有实际示例说明如何使 Azure Functions V4 与 NLog 配合使用并正确写入解决方案文件夹中的数据库和 .txt 文件。我只能在本地运行时才能登录控制台。
我注意到 appsettings.json 似乎无法与 NLog 和 Azure 功能一起使用,您必须创建 nlog.config 文件或 nlog.json 文件。
我尝试过使用这两个作为参考,但实际上都没有让我的代码正常工作。
使用 nlog.config 在 Azure Function Log Streams 中登录
https://github.com/NLog/NLog/issues/3538
是否有人有一个代码示例,可以实际使用必须放入 Startup.cs、AzureFunctions.cs 和 appsettings.json 文件中的内容?
我终于弄清楚了。
我使用了 Nuget 包...
NLog
NLog.Database
NLog.Extensions.Logging
NLog.Web.AspNetCore
Azure Functions V4 的 Startup.cs 的配置方法中的代码
var _logger = LogManager.Setup()
.SetupExtensions(e => e.AutoLoadExtensions())
.LoadConfigurationFromAppSettings(Path.Combine(builder.GetContext().ApplicationRootPath), null, "NLog", optional: false, reloadOnChange: true)
.LoadConfiguration(builder => builder.LogFactory.AutoShutdown = false)
.GetCurrentClassLogger();
builder.Services.AddLogging((loggingBuilder) =>
{
var nlogOptions = new NLogProviderOptions()
{
ShutdownOnDispose = true,
RemoveLoggerFactoryFilter = true
};
loggingBuilder.AddNLog(nlogOptions);
});
在ConfigureAppConfiguration中我放入...
var config = builder.ConfigurationBuilder
.SetBasePath(context.ApplicationRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: false)
.AddEnvironmentVariables().Build();