Introduction
Logging is a very critical and essential part of any software. It helps us in the investigation of the essence of problems. Before ASP.NET Core, we had to use third party libraries for logging our application.
ASP.NET Core has built-in support for logging APIs that is able to work with various logging providers. Using these built-in providers, we can send application logs to one or more destinations and also, we can plug in third party logging framework.
To use the built in logging feature of ASP.NET Core, first we need to add dependency of "Microsoft.Extensions.Logging" to project.json file. This dependency has common logging abstractions and a few implementations. We need to add more dependencies for adding the extension of this library.
For example, we need to add "Microsoft.Extensions.Logging.Console" as a dependency for writing log into console and need to add "Microsoft.Extensions.Logging.Debug" as a dependency for writing log in debug window. After updating the project.json file, we need to perform "dotnet restore" command to restore the dependency.
Project.json
- {
- "version" "1.0.0-*",
- "buildOptions" {
- "preserveCompilationContext" true,
- "debugType" "portable",
- "emitEntryPoint" true
- },
- "dependencies" {},
- "frameworks" {
- "netcoreapp1.0" {
- "dependencies" {
- "Microsoft.NETCore.App" {
- "type" "platform",
- "version" "1.0.1"
- },
- "Microsoft.AspNetCore.Server.Kestrel" "1.0.0",
- "Microsoft.AspNetCore.Mvc" "1.0.0",
- "Microsoft.Extensions.Logging" "1.1.0",
- "Microsoft.Extensions.Logging.Console" "1.1.0",
- "Microsoft.Extensions.Logging.Debug" "1.1.0",
- "Microsoft.Extensions.Logging.Filter" "1.1.0",
- "Microsoft.Extensions.Logging.TraceSource" "1.1.0",
- },
- "imports" "dnxcore50"
- }
- }
- }
- PM > Install - Package Microsoft.Extensions.Logging
Startup.cs
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Http;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Logging;
- namespace WebApplication {
- public class Startup {
- public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
- loggerFactory.AddConsole().AddDebug();...............
- }...............
- }
- }
- public class HomeController Controller {
- ILogger _logger;
- public HomeController(ILogger < HomeController > logger) {
- _logger = logger;
- }..........
- }
- LogCritical Formats and writes a critical log message.
- LogDebug Formats and writes a debug log message.
- LogError Formats and writes an error log message.
- LogInformation Formats and writes an informational log message.
- LogTrace Formats and writes a trace log message.
- LogWarning Formats and writes a warning log message.
In the following example, I have logged the some text using LogInformation and LogWarning method.
- [Route("home/LogData")]
- public IActionResult LogData() {
- _logger.LogInformation("Log Information to Debug Window!");
- _logger.LogWarning("Log Warning to Debug Window!");
- return View();
- }

The ILogger interface has method "Log". Using this method, we can also log the warning, information, etc. type of message. We need to specify the log level type to this method as parameter. The log level indicates the level of severity of logging statement. For example, "error" has more severity than the "warning".
The above methods (such as LogCritical, LogInformation etc.) are extension methods of log method. They internally pass the log level. We can also call the log method instead of these extension methods. The syntax of this method is relatively complicated. Log level has following possible values.
- Critical
- Debug
- Error
- Information
- None
- Trace
- Warning
Definition of LOG method
void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
Logging exceptions
Example
In the following example, the code has generated an error, “Input string was not in a correct format.” and caught and logged it as warning.
- [Route("home/LogException")]
- public IActionResult LogException() {
- try {
- int i = 0;
- i = Convert.ToInt32("");
- } catch (Exception ex) {
- _logger.LogWarning(1000, ex, "Log exception to Debug Window!");
- }
- return View("LogData");
- }

Log filtering
This feature allows us to specify which messages should be written to a storage medium or which should be ignored, based on the log level and category.
Every extension method (such as - AddDebug and AddConsole) provides overloads that allow us to pass filtering criteria. In the following example, console provider ignores the log's below mentioned warning level.
- public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
- loggerFactory.AddConsole(LogLevel.Warning);….….….
- }

Log scopes
Logging framework allows us to group a set of logical operations within the log scope, in order to assign the same data to each log which is part of this set.
To do this, first we need to enable scope for the provider. In the following example, I have enabled the scoping for console provider.
Startup.cs
- public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
- loggerFactory.AddConsole(includeScopes true).AddDebug();............
- }
- [Route("home/LogScope")]
- public IActionResult LogScope() {
- using(_logger.BeginScope("Log Scope Example")) {
- _logger.LogInformation("Log Information to Debug Window!");
- _logger.LogWarning("Log Warning to Debug Window!");
- }
- return View("LogData");
- }
Here, we can observe that every log message contains the scope information.

Built-in logging providers
ASP.NET Core provides the following built-in providers for logging.
- Console
- Debug
- EventSource
- EventLog
- TraceSource
- Azure App Service
Following providers work with ASP.NET Core logging framework
- elmah.io provider for the Elmah.Io service
- Loggr provider for the Loggr service
- NLog provider for the NLog library
- Serilog provider for the Serilog library
We can also create our own provider that uses other logging frames internally or has its own logging related requirement.
Summary
ASP.NET Core provides very basic yet powerful built-in logging framework. We can integrate this with third party logging frameworks, such as Nlog, Serilog etc. We can also create our own provider based on our requirement.

Indraneel PolePosted May 8, 2017, 12:15 PM
Is it possible to use the scope and log from two different classes to show scope of the logging from one class to another. (For example calling the Controller in the Startup class, and knowing with scope that Controller is called from the Startup class?)
Sajid AliPosted Dec 31, 2016, 3:13 AM
Good article really helpful. keep it up.
Mahesh ChandPosted Dec 29, 2016, 3:31 AM
Good one Jignesh. Nice to see more work on ASP.NET Core.
Manav PandyaPosted Dec 29, 2016, 2:48 AM
Nice explaination sir Jignesh Trivedi ji
Manoj KallaPosted Dec 29, 2016, 12:45 AM
Good one... Thank you sharing... How are you Jigneshbhai?