Azure / Azure/Azure-Functions

Injected ILogger using Autofac doesn't log anything on AzureFunctionTools window (AzureFunctionsV2)

Open
#1,317 3 comments 2 reactions 0 assignees View on GitHub
Dominant language
PowerShell
Stars
1.1k
Forks
215
Avg merge
4h 2m
Merged PRs (30d)
1

Description

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** 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();
services.AddScoped();

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()).As();

builder.RegisterType().As().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][1]][1]

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

[1]: https://i.stack.imgur.com/VCKTr.png

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.