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
- public class Startup: FunctionsStartup {
- public override void Configure(IFunctionsHostBuilder builder) {
- var config = new ConfigurationBuilder().AddJsonFile("local.settings.json", optional: true, reloadOnChange: true).AddEnvironmentVariables().Build();
- builder.Services.AddLogging();
-
- }
- }
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
- public class Startup: FunctionsStartup {
- private ILoggerFactory _loggerFactory;
- public override void Configure(IFunctionsHostBuilder builder) {
- var config = new ConfigurationBuilder().AddJsonFile("local.settings.json", optional: true, reloadOnChange: true).AddEnvironmentVariables().Build();
- builder.Services.AddLogging();
- ConfigureServices(builder);
- }
- public void ConfigureServices(IFunctionsHostBuilder builder) {
- _loggerFactory = new LoggerFactory();
- var logger = _loggerFactory.CreateLogger("Startup");
- logger.LogInformation("Got Here in Startup");
-
- }
- }
Conclusion
I hope this helps a lot of people. I really struggled to find this and get it working.