Add ILogger Reference at Startup in Azure Function

Introduction

 
ILogger interface is a part of .NET Framework that is used to write to a log file. The log file information can be the following types:
  • Info
  • Debug
  • Error
  • Warning
  • Critical
 
All the above-mentioned logging are the most common ones. But it may differ from project to project. You can also create your own custom log with your own naming convention.
 

Startup

  • Most projects use Dependency injection.
  • We have end number of services that are getting injected
We are resolving a lot of parameters and doing some validations even before the actual `Business Logic` executes. But what if something goes wrong there? How do I know what is wrong with my startup?
 

Functions Startup

 
It is also possible to get Ilogger reference directly in the startup and log your activities. How can you do it?
 
In Azure Functions, the startup class is inherited from FunctionsStartup and from which you get the `Configure` method where you build your IOC Container.
 
A simple Startup class will look like below piece of code
  1. public class Startup: FunctionsStartup {  
  2.     public override void Configure(IFunctionsHostBuilder builder) {  
  3.         var config = new ConfigurationBuilder().AddJsonFile("local.settings.json", optional: true, reloadOnChange: true).AddEnvironmentVariables().Build();  
  4.         builder.Services.AddLogging();  
  5.         //Do something with Builder to inject your services    
  6.     }  
  7. }  
Now to get logging working here, you have to make use of the `LoggerFactory ` to create an instance of `ILogger`. Here's how I got it working
  1. public class Startup: FunctionsStartup {  
  2.     private ILoggerFactory _loggerFactory;  
  3.     public override void Configure(IFunctionsHostBuilder builder) {  
  4.         var config = new ConfigurationBuilder().AddJsonFile("local.settings.json", optional: true, reloadOnChange: true).AddEnvironmentVariables().Build();  
  5.         builder.Services.AddLogging();  
  6.         ConfigureServices(builder);  
  7.     }  
  8.     public void ConfigureServices(IFunctionsHostBuilder builder) {  
  9.         _loggerFactory = new LoggerFactory();  
  10.         var logger = _loggerFactory.CreateLogger("Startup");  
  11.         logger.LogInformation("Got Here in Startup");  
  12.         //Do something with builder    
  13.     }  
  14. }  

Conclusion

 
I hope this helps a lot of people. I really struggled to find this and get it working.