在 Visual Studio 2017 中成功创建并运行简单的 Azure Durable Function 后,我想介绍一下日志记录。
Visual Studio 项目模板生成静态 HttpStart 类,其中包含 包含 Microsoft.Extensions.Logging.ILogger 类型的可选参数的 Run 方法。
我不知道如何将依赖项注入(inject)连接到持久功能项目中。谁能给我举个例子来说明如何实现这一目标?
在我看来,我需要一些类,在其中我需要使用 Microsoft.Extensions.Logging.LoggingFactory.CreateLogger() 方法。
我想这个逻辑需要位于一个容器类中,该容器类以某种方式使用 HostBuilder 连接到运行时管道(类似于在静态 main 方法中使用 WebHostBuilder)。
谢谢
最佳答案
@Thomas 向我指出了我用来提取代码的示例,这些代码允许在编写持久功能项目时使用依赖注入(inject):
using System.IO;
using System.Reflection;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Extensions.Logging;
using tmetadastoreFnApp;
using Willezone.Azure.WebJobs.Extensions.DependencyInjection;
using ILogger = Microsoft.Extensions.Logging.ILogger;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
[assembly: WebJobsStartup(typeof(Startup))]
namespace tmetadastoreFnApp
{
internal class Startup : IWebJobsStartup
{
public void Configure(IWebJobsBuilder builder) =>
builder.AddDependencyInjection(ConfigureServices);
private void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ILoggerFactory, LoggerFactory>();
services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
services.AddLogging((builder) => builder.SetMinimumLevel(LogLevel.Trace));
var serviceProvider = services.BuildServiceProvider();
var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true });
var dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
LogManager.LoadConfiguration(Directory.GetParent(dir) + "\\nlog.config");
}
}
}
关于function - 有关如何连接持久函数依赖注入(inject)的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53092076/