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:
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?
