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. public IConfigurationRoot Configuration { get; }
  13. // This method gets called by the runtime. Use this method to add services to the container.
  14. public void ConfigureServices(IServiceCollection services)
  15. {
  16. // Add framework services.
  17. services.AddMvc();
  18. services.AddLogging();
  19. }
  20. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  21. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  22. {
  23. loggerFactory.AddConsole(Configuration.GetSection("Logging"));
  24. loggerFactory.AddDebug();
  25. if (env.IsDevelopment())
  26. {
  27. app.UseDeveloperExceptionPage();
  28. app.UseBrowserLink();
  29. }
  30. else
  31. {
  32. app.UseExceptionHandler("/Home/Error");
  33. }
  34. app.UseStaticFiles();
  35. app.UseMvc(routes =>
  36. {
  37. routes.MapRoute(
  38. name: "default",
  39. template: "{controller=Home}/{action=Index}/{id?}");
  40. });
  41. }
  42. }
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. public HomeController(ILoggerFactory Mylogger)
  5. {
  6. _logger = Mylogger.CreateLogger(typeof(HomeController));
  7. }
  8. public IActionResult Index()
  9. {
  10. return View();
  11. }
  12. public IActionResult About()
  13. {
  14. try
  15. {
  16. ViewData["Message"] = "Your application description page.";
  17. _logger.LogInformation("About Page has been Accessed");
  18. return View();
  19. }
  20. catch (System.Exception ex)
  21. {
  22. _logger.LogError("About: " + ex.Message);
  23. throw;
  24. }
  25. }
  26. public IActionResult Contact()
  27. {
  28. try
  29. {
  30. ViewData["Message"] = "Your contact page.";
  31. _logger.LogInformation("Contact Page has been Accessed");
  32. return View();
  33. }
  34. catch (System.Exception ex)
  35. {
  36. _logger.LogError("Contact: " + ex.Message);
  37. throw;
  38. }
  39. }
  40. public IActionResult Error()
  41. {
  42. return View();
  43. }
  44. }
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.