Built-In Logging In .NET Core

Introduction

For an application, logging is very important to keep track of that application and keep it error-free. In .NET Core, we don't need any third party logging; instead, we can use built-in logging whenever we want. This is very efficient in terms of code and performance.
 
Let’s start.

Create a new .NET Core application and name it.



Step 1: 
Go to Package mManager View-->Other Windows--> Package manager Console  -->
 
 Install-Package Microsoft.Extensions.Logging



Add Logging

Once  the extension's installed, we can add logging by adding ILogger<T> (custom logging) or ILoggerFactory. If we want to use ILoggerFactory, then we must create it using CreateLogger, to use logging add logging services under ConfigureServices. Moreover, we can use built-in logging with the other loggings (like Nlog) with very minimal code. 
  1. services.AddLogging();  
Startup.cs 
  1. public class Startup  
  2.     {  
  3.         public Startup(IHostingEnvironment env)  
  4.         {  
  5.             var builder = new ConfigurationBuilder()  
  6.                 .SetBasePath(env.ContentRootPath)  
  7.                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)  
  8.                 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)  
  9.                 .AddEnvironmentVariables();  
  10.             Configuration = builder.Build();  
  11.         }  
  12.   
  13.         public IConfigurationRoot Configuration { get; }  
  14.   
  15.         // This method gets called by the runtime. Use this method to add services to the container.  
  16.         public void ConfigureServices(IServiceCollection services)  
  17.         {  
  18.             // Add framework services.  
  19.             services.AddMvc();  
  20.             services.AddLogging();  
  21.         }  
  22.   
  23.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  24.         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
  25.         {  
  26.             loggerFactory.AddConsole(Configuration.GetSection("Logging"));  
  27.             loggerFactory.AddDebug();  
  28.   
  29.             if (env.IsDevelopment())  
  30.             {  
  31.                 app.UseDeveloperExceptionPage();  
  32.                 app.UseBrowserLink();  
  33.             }  
  34.             else  
  35.             {  
  36.                 app.UseExceptionHandler("/Home/Error");  
  37.             }  
  38.   
  39.             app.UseStaticFiles();  
  40.   
  41.             app.UseMvc(routes =>  
  42.             {  
  43.                 routes.MapRoute(  
  44.                     name: "default",  
  45.                     template: "{controller=Home}/{action=Index}/{id?}");  
  46.             });  
  47.         }  
  48.     }  
ILoggerFactory: We can use  ILoggerFactory. For this, we must use CreateLogger. 
  1. _logger = Mylogger.CreateLogger(typeof(HomeController));  
HomeController.cs 
  1. public class HomeController : Controller  
  2.     {  
  3.         private ILogger _logger;  
  4.   
  5.         public HomeController(ILoggerFactory Mylogger)  
  6.         {  
  7.             _logger = Mylogger.CreateLogger(typeof(HomeController));  
  8.         }  
  9.   
  10.         public IActionResult Index()  
  11.         {  
  12.             return View();  
  13.         }  
  14.   
  15.         public IActionResult About()  
  16.         {  
  17.             try  
  18.             {  
  19.                 ViewData["Message"] = "Your application description page.";  
  20.                 _logger.LogInformation("About Page has been Accessed");  
  21.                 return View();  
  22.             }  
  23.             catch (System.Exception ex)  
  24.             {  
  25.                 _logger.LogError("About: " + ex.Message);  
  26.                 throw;  
  27.             }  
  28.         }  
  29.   
  30.         public IActionResult Contact()  
  31.         {  
  32.             try  
  33.             {  
  34.                 ViewData["Message"] = "Your contact page.";  
  35.                 _logger.LogInformation("Contact Page has been Accessed");  
  36.                 return View();  
  37.             }  
  38.             catch (System.Exception ex)  
  39.             {  
  40.                 _logger.LogError("Contact: " + ex.Message);  
  41.                 throw;  
  42.             }  
  43.         }  
  44.   
  45.         public IActionResult Error()  
  46.         {  
  47.             return View();  
  48.         }  
  49.     }  
Run and Test



LogLevel: We can add logging level by adding the level we want in appsettings.json.
  • Trace
  • Debug
  • Information
  • Warning
  • Error
  • Application failure or crashes                   
Summary

We can use built-in logging frameworks and separate our application from logger implementation so that we can use the same framework later for other logging providers.

Up Next
    Ebook Download
    View all
    Learn
    View all