BorisWilhelms / azure-function-dependency-injection

Dependency Injection for Azure Functions v2
https://blog.wille-zone.de/
MIT License
145 stars 45 forks source link

Logging scopes seems to be not populated on Autofac container #40

Open joaoantunes opened 5 years ago

joaoantunes commented 5 years ago

I'm new on Azure Functions, and I've tried to use Autofac as the container of DI on the application.

There are some services there are registered automatically by the function on the .Net DI like for example the logging providers.

When I tried to use ILogger abstraction of Microsoft, I had an issue that was logging nothing on my custom classes, that were resolved by the Autofac, but all functions were able to log properly since that ILogger is resolver by .Net DI.

So I assume that services registered .Net DI are not on Autofac! I've registered some manually to get Console logs and ApplicationLogs example:

public class WebJobsStartup : IWebJobsStartup
{

    public void Configure(IWebJobsBuilder builder) =>
     builder.AddDependencyInjection<AutoFacServiceProviderBuilder>();
}
public class AutoFacServiceProviderBuilder : IServiceProviderBuilder
{
    private readonly IConfiguration configuration;

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

    public IServiceProvider Build()
    {
        // Had to install:
        // - Microsoft.Extensions.Logging.Console 
        // - Microsoft.Extensions.Logging.Debug 
        // - Microsoft.Extensions.Logging.ApplicationInsights 

        var services = new ServiceCollection();
        services.AddLogging(l => l.AddConsole()
        .AddDebug()
        // Had to insert the ApplicationInsights key manually because was not working using the EnviromentVariable
        // check here: https://stackoverflow.com/questions/50717398/whats-the-difference-between-appinsights-instrumentationkey-configured-by-azure
        .AddApplicationInsights("Insert-AI-Key")); 

        var builder = new ContainerBuilder();
        builder.RegisterType<SingletonService>().As<ISingletonService>().SingleInstance();

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

The problem is that I had to find out about those Extensions (AddLogging with all the providers) and scopes seem to be not working. When I log using the ILogger on custom function comparing to the ILogger on function it misses some valuable information such as:

The most importante was to get the same OperationId as the function, since I want to correlate logs to the function call, so I have a way of tracking issues.

Any Idea why this is not working? I think is because probably since I need to manually program ApplicationInsights telemetries & scopes since they are not being populated on Autofac.

So my final questions are: