Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register ASP.NET Core ILogger<> from built-in logging mechanism to Autofac

I have a ASP.NET Core app using Autofac as DI container. I'm also using built-in logging mechanism that provides ILogger<> dependency. Now I'd like to register it in Autofac. How?

like image 871
Andrzej Avatar asked Aug 20 '18 07:08

Andrzej


People also ask

How to create ILogger in ASP NET Core?

To create logs, use an ILogger<TCategoryName> object. In a web app or hosted service, get an ILogger from dependency injection (DI). In non-host console apps, use the LoggerFactory to create an ILogger. The following ASP.NET Core example creates a logger with TodoApiSample.Pages.AboutModel as the category.

How do I create a logging provider in ASP NET Core?

Creating a logging provider is relatively easy in ASP.NET Core as you can build the functionality around methods that are contained in the ILogger and ILoggerProvider interfaces. We will have a look at creating and implementing a logging provider so it we can log to a table in a SQL Server database.

How do I write logs to files from an ASP core app?

ASP.NET Core doesn't include a logging provider for writing logs to files. To write logs to files from an ASP.NET Core app, consider using a third-party logging provider.

How to use ILogger/iloggerfactory anywhere in an application?

We can use ILogger or ILoggerFactory anywhere in an application using ASP.NET Core DI (Dependency Injection). Consider the following example of HomeController : In the above example, the ILogger<HomeController> parameter is included in the constructor. ASP.NET Core DI will pass the ILogger instance, which can be used to log in the Index () ...


1 Answers

As already stated, when you use the official autofac-integration for asp.net-core you don't need to do anything. If you still want to do it manually, which is legit, you could do the following in the ConfigureContainer method.

public void ConfigureContainer(ContainerBuilder builder)
{
   // ... more registrations
   builder.RegisterInstance(new LoggerFactory())
                .As<ILoggerFactory>();

   builder.RegisterGeneric(typeof(Logger<>))
          .As(typeof(ILogger<>))
          .SingleInstance();
}

Keep in mind that their is no specific logging-provider added.

like image 182
alsami Avatar answered Oct 20 '22 18:10

alsami