首页 > 解决方案 > Azure WebJob,ILogger DI 注入日志到 BlobStorage

问题描述

我主要为我的 API 构建服务,因此它们都在其构造函数中注入了 ILogger<>。(Azure 网络应用)

现在我也在 Azure 中使用 Web 作业,并按照以下说明使用 DI 构建它:https ://matt-roberts.me/azure-webjobs-in-net-core-2-with-di-and-configuration/

我现在的问题是,我希望 service.logger 实例登录到 Azure BlobStorage 以进行 Web 作业。通过绑定,我得到了时间触发函数的 ILogger 实例。但是如何将服务日志记录到 BobStorage?

提前致谢。

loggerFactory.AddConsole();
loggerFactory.AddAzureWebAppDiagnostics();

public async Task TimeJob(
    [TimerTrigger("0 */5 * * * *", RunOnStartup = true)] TimerInfo timerInfo,
    ILogger log
    )
    ....

编辑

IServiceCollection services = new ServiceCollection()
.AddLogging(config =>
{
    config.AddConfiguration(configuration.GetSection("Logging"));
    config.AddConsole();
    config.AddAzureWebAppDiagnostics();
 })
 .AddSingleton(configuration)
 ;

 // register services and such
 configurationCallback(services);

 return services.BuildServiceProvider();

.

        Program.Configuration = SetupHelper.SetupConfiguration(args);
        Program.Services = SetupHelper.SetupServiceProvider(Program.Configuration, Program.ConfigureServices);
        var loggerFactory = Program.Services.GetService<ILoggerFactory>();

        var hostConfig = new JobHostConfiguration(Program.Configuration)
        {
            JobActivator = new CustomJobActivator(Program.Services),
            LoggerFactory = loggerFactory
        };
        hostConfig.Queues.MaxPollingInterval = TimeSpan.FromSeconds(10);
        hostConfig.Queues.BatchSize = 1;
        hostConfig.UseTimers();

        //hostConfig.Tracing.ConsoleLevel = TraceLevel.Off;

        if (hostConfig.IsDevelopment)
        {
            hostConfig.UseDevelopmentSettings();
        }

        var host = new JobHost(hostConfig);
        host.RunAndBlock();

样品服务

public abstract class Service : IService
{
    protected readonly ILogger Logger;
    protected readonly IUserInfo UserInfo;
protected bool Disposed;

protected Service(
    ILogger logger,
    IUserInfo userInfo)
{
    this.Logger = logger;
    this.UserInfo = userInfo;
}

public abstract void Dispose();

标签: azureloggingdependency-injectionazure-webjobs

解决方案


我按照您提供的教程下载演示

您可以参考以下步骤登录 Blob 存储。Nuget 包: 在此处输入图像描述

时间工作:

public void DoSomethingUseful([TimerTrigger("0 */1 * * * *", RunOnStartup = true)] TimerInfo timerInfo, ILogger log)
        {
            // Act on the DI-ed class:
            string thing = _usefulRepository.GetFoo();
            Console.WriteLine($"{DateTime.Now} - {thing}");
            ILoggerFactory loggerFactory = new LoggerFactory()
            .AddConsole()
            .AddDebug()
            .AddAzureWebAppDiagnostics();

            log = loggerFactory.CreateLogger<SampleScheduledWebJob>();

            log.LogInformation("hello world");

        }

部署到 azure 后,我可以看到 KUDU 控制台下的日志和 blob 日志文件,如下所示: 在此处输入图像描述

在此处输入图像描述


推荐阅读