Effortless Logging In .Net Core and Asp.Net Core version > 2

Logging In Asp.Net Core

.Net core support a variety of built-in and third-party providers.

The Logging API is included in the Microsoft.Extensions.Logging package. The Logging API does not work as a standalone. It works with one or more logging providers that store or display logs to a particular medium such as Console, Debug, Trace Listeners, etc.

So, there are two important building blocks for implementing logging in a .NET Core based application:

  1. Logging API
  2. Logging Providers

Microsoft.Extensions.Logging includes the necessary classes and interfaces for logging. The most important is the ILogger, ILoggerFactory, ILoggerProvider interfaces, and the LoggerFactory class.

You can see the code in CreateDefaultBuilder method of WebHost class. You call this in the main method of program class below is the code for that.

public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }

This method is responsible for setting a server and load application configuration from various configuration and also responsible for logging. See below the image in that you clearly see WebHost class’s CreateDefaultBuilder method responsible for load and read logging configuration information.

add logging configuration asp.net core

To enable log we need to add below configuration in appsetting.js file

"Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Microsoft": "Information" 
    }
  }
appsetting.json

After running this project you will see the output is printed on the output window in visual studio.

So if you check the lot’s of information is logged on output window and Verbose logs are written to:

C:\Users\Sagar\AppData\Local\Temp\vscode-chrome-debug.txt

The module is optimized and the debugger option ‘Just My Code’ is enabled.

Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager:Information: User profile is available. Using 'C:\Users\Sagar\AppData\Local\ASP.NET\DataProtection-Keys' as key 
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App\2.2.7\Microsoft.AspNetCore.HttpsPolicy.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is 
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/2.0 GET https://localhost:44387/  
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App\2.2.7\Microsoft.AspNetCore.Http.Extensions.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
My Code' is enabled.
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.2.7\System.Transactions.Local.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App\2.2.7\System.Interactive.Async.dll'. Symbols loaded.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executing action method LearnAspCore.Controllers.HomeController.Index (LearnAspCore) - Validation state: Valid
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action method LearnAspCore.Controllers.HomeController.Index (LearnAspCore), returned result Microsoft.AspNetCore.Mvc.ViewResult in 1.4381ms.
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor:Information: Executing ViewResult, running view Index.
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.2.7\System.Reflection.Extensions.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Microsoft.EntityFrameworkCore.Infrastructure:Information: Entity Framework Core 2.2.6-servicing-10079 initialized 'OurDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: MaxPoolSize=128 
Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (11ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [s].[StudentId], [s].[Address], [s].[Division], [s].[FullName], [s].[PhotoPath]
FROM [Students] AS [s]
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.2.7\Microsoft.CSharp.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor:Information: Executed ViewResult - view Index executed in 739.5409ms.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action LearnAspCore.Controllers.HomeController.Index (LearnAspCore) in 1108.6874ms
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 1331.2128ms 200 text/html; charset=utf-8
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/2.0 GET https://localhost:44387/lib/jquery/jquery.js  
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/2.0 GET https://localhost:44387/lib/bootstrap/css/bootstrap.css  
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/2.0 GET https://localhost:44387/lib/bootstrap/js/bootstrap.js  
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware:Information: Sending file. Request path: '/lib/jquery/jquery.js'. Physical path: 'C:\Users\Sagar\source\repos\LearnAspCore\wwwroot\lib\jquery\jquery.js'
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware:Information: Sending file. Request path: '/lib/bootstrap/css/bootstrap.css'. Physical path: 'C:\Users\Sagar\source\repos\LearnAspCore\wwwroot\lib\bootstrap\css\bootstrap.css'
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware:Information: Sending file. Request path: '/lib/bootstrap/js/bootstrap.js'. Physical path: 'C:\Users\Sagar\source\repos\LearnAspCore\wwwroot\lib\bootstrap\js\bootstrap.js'
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 107.9707ms 200 text/css
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 82.6069ms 200 application/javascript
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 153.7231ms 200 application/javascript
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/2.0 GET https://localhost:44387/favicon.ico  
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 7.4146ms 404 
Failed to load resource: the server responded with a status of 404 () [https://localhost:44387/favicon.ico]

If you run your project from the command line you can get log information on command prompt.

Built-in Logging Providers:

Logging Providers

  • Console
  • Debug
  • EventLog
  • AzureApp
  • Trace
  • Event

Logging Levels

  • Trace
  • Debug
  • Info
  • Warning
  • Error
  • Critical
  • None
  1. Console: – It displays logs on the console window
  2. EventLog:- if you have windows operating system it will add logs in the event log.
  3. AzureAppServiceFile:- provider logs data to azure app service file.

Above are inbuilt log providers but also we have some third party logs providers.

Third-Party Logging Providers in Asp.Net Core

  1. NLog
  2. Serilog
  3. Sentry
  4. Gelf
  5. JSNLog
  6. Loggr

How to log exception and warning to file using third party log providers in asp.net core?

  • To log the information we need to include Ilogger interface and inject that Logger object into the constructor of our controller where you want to log error messages.
public class ErrorController : Controller
    {

       private ILogger<ErrorController> LoggerObjetct { get; set; }

        public ErrorController(ILogger<ErrorController> logger)
        {
            this.LoggerObjetct = logger;
        } 
}
  • Specify the type of the Controller into which ILogger is injected as a generic argument

How to log exception and warning to file using third party log providers in asp.net core?

  • To log the information we need to include Ilogger interface and inject that Logger object into the constructor of our controller where you want to log error messages.
public class ErrorController : Controller
    {
        private ILogger<ErrorController> LoggerObjetct { get; set; }
        public ErrorController(ILogger<ErrorController> logger)
        {
            this.LoggerObjetct = logger;
        }
}
  • Specify the type of the Controller into which ILogger is injected as a generic argument.
  • Below is some instance methods are given for logging messages
  1. LogError
  2. LogCritical
  3. LogDebug
  4. LogInformation
  5. Etc…
LogObject Method

How to log in a text file in Asp.net core by using NLog?

NLog is third-party provider and link for this https://www.nuget.org/packages/NLog.Web.AspNetCore/

NLog Package Nugget

After installing Nlog you required to add some configuration in nlog.config file in your project. For that you need to create nlog.config file in your project it is not added by default like below.

NLog config file addition
NLog config file addition 2

You will copy a minimum configuration in our file like below. I use the below sample

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="Trace"
      internalLogFile="d:\work\log.txt">


  <!-- define various log targets -->
  <targets>
    <!-- write logs to file -->
    <!--<target xsi:type="File" name="file" fileName="${basedir}/logs/${shortdate}.log"
            layout="${longdate} ${aspnet-request:servervariable=URL} ${uppercase:${level}} ${message}" />-->
    <target xsi:type="File" name="file" fileName="C:\Users\Sagar\source\repos\LearnAspCore\bin\Debug\netcoreapp2.2\logfile-${shortdate}.log"
            layout="${longdate} ${aspnet-request:servervariable=URL} ${uppercase:${level}} ${message}" />
  </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="allOutputs" />
  </rules>
</nlog>

By Using NLog you can write logs in database send to server using gmail and in file format.

You can also refer https://nlog-project.org/config/ this link in which you can find several resources on that and for file https://github.com/NLog/NLog/wiki/File-target this is sample.

After this next step is to add configuration in CreateWebHostBuilder method in program.cs file the code looks like below

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureLogging((context, logging) =>
                    {
                        logging.AddConfiguration(context.Configuration.GetSection("Logging"));
                        logging.AddConsole();
                        logging.AddDebug();
                        logging.AddEventSourceLogger();
                        logging.AddNLog();
                    })
                .UseStartup<Startup>();

Steps to Use nlog

  1. Install NLog.Web.AspNetCore nugget package
  2. After adding package Nlog looking for configuration file and for that we need to add nlog.config file in our project at root location after this you need to a configuration in our nlog.config file
  3. Enable copy operation of nlog.config file
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="Trace"
      internalLogFile="d:\work\log.txt">


  <!-- define various log targets -->
  <targets>
    <!-- write logs to file -->
    <target xsi:type="File" name="file" fileName="C:\Users\Sagar\source\repos\LearnAspCore\bin\Debug\netcoreapp2.2\logfile-${shortdate}.log"
            />
  </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="allOutputs" />
  </rules>
</nlog>
  1. Add Nlog as logging provider in our CreateWebHostBuilder method
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureLogging((context, logging) =>
                    {
                        logging.AddConfiguration(context.Configuration.GetSection("Logging"));
                        logging.AddConsole();
                        logging.AddDebug();
                        logging.AddEventSourceLogger();
                        logging.AddNLog();
                    })
                .UseStartup<Startup>();

Above configuration add 2 files at 2 different location one is inside the project folder and one is D:/work these paths are given in nlog.config file you can check there.

Log level configuration in asp.net core

Loglevel indicates the severity of the logged messages

Log level configuration

These options are available in using Microsoft.Extensions.Logging; namespace and loglevel is enum.

Log Level enum internal

Whatever we have loglevel enum we have a corresponding method for that except none, in ILggoer object which we injected in the constructor of error controller or homecontroller.

The output of this logger messages

You can specify log level to every configuration means for log level values like debug,trace and like that.

Sagar Jaybhay, from Maharashtra, India, is currently a Senior Software Developer. He has continuously grown in the roles that he has held in the more than seven years he has been with this company. Sagar Jaybhay is an excellent team member and prides himself on his work contributions to his team and company as a whole.

Related posts