使用Autofac注入的ILogger不会在AzureFunctionTools窗口(AzureFunctionsV2)上记录任何内容

时间:2019-09-06 09:33:03

标签: c# logging azure-functions autofac

我正在使用 Microsoft.Extensions.Logging 的ILogger抽象来进行一些日志记录。

如果我在“ Azure函数的运行”中进行日志记录,它将记录到“ AzureFunctionTools”窗口中,没有任何问题。

但是我还需要在应用程序的其他类中记录日志,不仅是在azure函数上,而且我想使用同一系统!

我正在使用 Autofac作为DI ,如on this answer所述 因此,阅读一段时间后,我这样做了:

public class AutoFacServiceProviderBuilder : IServiceProviderBuilder
{
    private readonly IConfiguration configuration;

    public AutoFacServiceProviderBuilder(IConfiguration configuration) 
        => this.configuration = configuration;

    public IServiceProvider Build()
    {
        var services = new ServiceCollection();
        services.AddTransient<ITransientService, TransientService>();
        services.AddScoped<IScopedService, ScopedService>();

        var builder = new ContainerBuilder();

        // Registered the ILoggerFactory to provide the logger
        // on the classes where is logging a need 
        builder.Register(s => services.AddLogging().BuildServiceProvider()
            .GetService<ILoggerFactory>()).As<ILoggerFactory>();

        builder.RegisterType<SingletonService>().As<ISingletonService>().SingleInstance(); 

        builder.Populate(services);
        return new AutofacServiceProvider(builder.Build());
    }
}

然后在这里,我在与AzureFunction不同的类上使用了日志记录:

public class TransientService : ITransientService
{
    private readonly ILogger logger;
    private int counter = 0;

    public TransientService(ILoggerFactory loggerFactory)
    {
        // I've used this logger name because I've read this (written in 27/May/2018):
        // here: https://www.neovolve.com/2018/04/05/dependency-injection-and-ilogger-in-azure-functions/
        // Azure Functions(v2 beta) applies a filter out of the box for ILogger.The filter looks
        // at whether the logger name is either Function.Something or Function.Something.User.Any 
        // logger that does not have its name matching this format will have its log messages filtered out.
        string loggerName = "Function." + typeof(LazyExample).FullName + ".User";
        this.logger = loggerFactory.CreateLogger(loggerName);
        this.logger.LogError($"I'm creating the class: {nameof(LazyExample)}");
    }

    public int GetCounter()
    {
        this.logger.LogInformation($"Counting {this.counter} on {nameof(TransientService)} class.");
        return this.counter++;
    }
}

在下图中,您可以看到在该函数上创建的日志或azure函数的内部登录记录,但是我的日志没有显示:

Result when I run the function

我也更改了host.json,但是我在服务上的日志仍然没有记录:

{
  "version": "2.0",
  "logging": {
    "fileLoggingMode": "debugOnly",
    "logLevel": {
      "default": "Trace"
    },
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "maxTelemetryItemsPerSecond": 5
      }
    }
  }
}

如何重用Microsoft在自己的类上提供并由Autofac注入的Logger实现?

0 个答案:

没有答案