Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Microsoft.Extensions.Logging<T> in console application using Serilog and AutoFac?

Tags:

We have common BL classes in a ASP.NET Core application that get in the ctor:

Microsoft.Extensions.Logging.ILogger<Foo>

In ASP.NET Core, the internal infrastructure of ASP.NET handles getting the ILogger via the LoggerFactory.

We now want to reuse these BL classes in a console application (for async jobs), how do we setup AutoFac and Serilog to inject Microsoft.Extensions.Logging.ILogger<T> in environment that LoggerFactory doesn't exists?

like image 483
gdoron is supporting Monica Avatar asked Jan 01 '17 10:01

gdoron is supporting Monica


People also ask

What is the use of Microsoft extensions logging?

Extensions. Logging provided by ASP.NET Core. This provides an ILogger interface that allows the provider of your choice to be used while minimizing the impact to existing code.

How do I enable Serilog?

Install the Serilog NuGet packages To do this, select the project in the Solution Explorer window and right-click and select “Manage NuGet Packages...” In the NuGet Package Manager window, search for the following packages and install them.


1 Answers

Microsoft.Extensions.Logging (see source) is not part of ASP.NET Core and can run independently of it. All you need to do is to register the ILoggerFactory and ILogger<> interface.

The ILoggerFactory is used by Logger<T> to instantiate the actual logger.

When using the Logging extension in console applications, its recommended still to use the IServiceCollection, as this allows you to use the IServiceCollection extension methods to register all packages which support this pattern.

var services = new ServiceCollection(); services.AddLogging();  // Initialize Autofac var builder = new ContainerBuilder(); // Use the Populate method to register services which were registered // to IServiceCollection builder.Populate(services);  // Build the final container IContainer container = builder.Build(); 

This is the recommended approach, as you won't have to think in detail which classes need to registered for libraries which have Microsoft.Extensions.DependencyInjection integration support.

But of course you can also register it manually, but when a change happens to the Microsoft.Extensions.Logging library (new dependency added), you won't get it and first have to figure out or dig into the source code to find the error.

builder.RegisterType<LoggerFactory>()     .As<ILoggerFactory>()     .SingleInstance(); builder.RegisterGeneric(typeof(Logger<>))     .As(typeof(ILogger<>))     .SingleInstance(); 

All that remains is to register the logger types after the container has been built or before your application starts:

var loggerFactory = container.Resolve<ILoggerFactory>(); loggerFactory.AddConsole()     .AddSerilog(); 

and in your services inject ILogger<MyService> as usual.

like image 183
Tseng Avatar answered Sep 21 '22 06:09

Tseng