

public class ValuesController : Controller Also, because it is stored in the services collection that later gets set on each HttpContext, you can potentially access it that way. Dependency injection can give you the factory or a logger either one. In the example code below, I am showing off 3 different ways to access the LoggerFactory from your MVC controller.

Services.AddSingleton(this._loggerFactory) Īccessing the LoggerFactory Object via Dependency Injection and Services Using (List.Enumerator enumerator = this._configureLoggingDelegates.GetEnumerator()) This._loggerFactory = (ILoggerFactory) new LoggerFactory() Services.AddSingleton(this._hostingEnvironment) ServiceCollection services = new ServiceCollection() private IServiceCollection BuildHostingServices() This process under the covers ultimately calls some code in the WebHostBuilder class that creates a new LoggerFactory() and stores the reference to it in the ServicesCollection and the WebHostBuilder itself. UseContentRoot(Directory.GetCurrentDirectory()) When your app starts up you use the WebHostBuilder to essentially start up Kestrel and your web server. If you are like me, you immediately want to know what calls Configure() and where the ILoggerFactory instance actually came from and live at. LoggerFactory.AddDebug() //does all log levels LoggerFactory.AddConsole(Configuration.GetSection("Logging")) //log levels set in your configuration public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) This is where you can add providers to the ILoggerFactory for things like Debug & Console but also more advanced things like ETW or 3rd party providers. The biggest of those is being able to actually write your logs to a file on disk! Where is the LoggerFactory Created?įor an ASP.NET Core, you first see the ILoggerFactory within your Startup class that looks something like this below. By using it in this way, it also allows you to leverage all of the power of a library like NLog to overcome any limitations the built-in API may have. So you can use the ILoggerFactory and it ends up working sort of like Common.Logging does as a facade above an actual logging library. Other logging frameworks like NLog and Serilog have even written providers for it. The logging API supports multiple output providers and is extensible to potentially be able to send your application logging anywhere. It is designed as a logging API that developers can use to capture built-in ASP.NET logging as well as for their own custom logging. Basics of the .NET Core Logging With LoggerFactory
