- Starting with an empty .NET Core Console Application add the following packages:
Microsoft.Extensions.DependencyInjection
Microsoft.Extensions.Logging
Microsoft.Extensions.Logging.Console
- Instantiate Microsoft’s Dependecy Injection Service Provider.
var serviceProvider = new ServiceCollection().BuildServiceProvider();
- Register the Console Logging Provider dependency with the Service Provider using Microsoft’s extension methods
var serviceProvider = new ServiceCollection().AddLogging(cfg => cfg.AddConsole()).BuildServiceProvider();
By default the lifetime of the logging service is set to Singleton.
- Add configuration to the Logging Provider if required
var serviceProvider = new ServiceCollection().AddLogging(cfg => cfg.AddConsole()).Configure<LoggerFilterOptions>(cfg => cfg.MinLevel=LogLevel.Debug).BuildServiceProvider();
- Inject the Singleton instance of the logger into a variable from the Service Provider.
var logger = serviceProvider.GetService<ILogger<Program>>();
The type
Program
and it’s namespace are used by the logger as a category name for the logging output.
- You can now use the logger
logger.LogDebug("Woo Hooo");
dbug: Namespace.Program[0] Woo Hooo
Of course you can replace Microsoft’s Service Provider with any other DI Framework (Autofac, Structure Map) and the Logging Provider with any other Logging Provider (Serilog, Log4Net).
Complete Solution
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
class Program
{
static void Main(string[] args)
{
// instantiate DI and configure logger
var serviceProvider = new ServiceCollection().AddLogging(cfg => cfg.AddConsole()).Configure<LoggerFilterOptions>(cfg => cfg.MinLevel=LogLevel.Debug).BuildServiceProvider();
// get instance of logger
var logger = serviceProvider.GetService<ILogger<Program>>();
// use the logger
logger.LogDebug("Woo Hooo");
}
}