1

I'm using ILogger abstraction of Microsoft.Extensions.Logging in other to do some logging.

If I do the logging in the Run of the Azure Function it logs to the AzureFunctionTools window without any issues.

But I need logs also in other classes of the application, not only on azure functions, and I want to use the same system!

I'm using Autofac as DI as been described on this answer So after reading a while I did this:

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());
    }
}

Then here I've used the logging on a class different than 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++;
    }
}

In the following image you can see the logs that were made on the function or the internal loggins of azure functions, but my loggings doesn't show:

Result when I run the function

I've also changed my host.json but my loggings on my service still doesn't log:

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

How can I reuse Logger implementation provided by Microsoft on my own classes and injected by Autofac?

João Antunes
  • 798
  • 8
  • 27
  • How is the `Build()` method being called ? Do you need autofac ? Won't the function DI suffice your needs? – HariHaran Sep 09 '19 at 05:04
  • Agreed with HariHaren- could you please provide the reasoning behind Autofac? Functions v2 supports ILogger without custom injection. I would guess that your Autofaq version is creating a second logger that isn't connected with AI. Since the article you referenced was written Functions has stopped using custom logging in the portal and it all goes through App Insights. https://github.com/Azure/azure-functions-host/wiki/ILogger – PerfectlyPanda Sep 09 '19 at 17:57
  • @HariHaran I've updated the question with a link where I explain how I've configured the build to call the above IServiceProviderBuilder. Here is the link also: https://stackoverflow.com/questions/57773329/proper-way-of-registering-3rd-party-di-framework-lamar-autofac-on-azure-functi/57784893?noredirect=1#comment102023896_57784893 . I want to use Autofac to have more DI functionalities like Interceptors, Lazy loading, etc,, is not directly related with the logger, but since now my classes are resolved by Autofac, If I want to use the logger there I need to facilitate a way of doing it. – João Antunes Sep 10 '19 at 15:14
  • @SamaraSoucy-MSFT Here it explains what I wanted to do: https://blog.stephencleary.com/2018/06/microsoft-extensions-logging-part-2-types.html . ILoggerFactory is responsible to create an instance logger and should log to all available (registered) ILoggerProdiver. What I think is happening is that the LoggerProvider that logs to AzureFunction window on debugging is not registered. The problem is what Provider do I need to register? Console? I've tried AddConsole of nugget: Microsoft.Extensions.Logging.Console but the result was the same :( – João Antunes Sep 11 '19 at 16:00
  • I think I've found the solution! The first issue was that I needed to add the Console logging provider. The second was the order of register since I was registering before on the container and then populating the ServiceCollections all my changes were overwritten. Soon I'll post the final solution. – João Antunes Sep 11 '19 at 17:41
  • @JoãoAntunes Would you mind posting the answer to help others? – Tom Luo Oct 10 '19 at 09:19

0 Answers0