ttmind

Main Navigation

ttmind
  • jim-jams
  • Tech
  • Positive
Login

Login

Facebook Google

OR

Remember me Forgot password?

Don't have account? Signup here.

Sort by Categorys

.Net

PHP

Java

JavaScript

Database

Server

Client Side

Tools

Artificial Intelligence

Cloud

Hybrid Development

Event

Smart City

Education

Security

Scrum

Digital Marketing

APP Development

Business

Internet

Simulation

Art

Network

Microservices

Architecture

Technology

Leadership

    Top Articles

  • How Does Social Media Bring People Together?
    TTMind Author
  • How to read appSettings JSON from Class Library in ASP.NET Core
    Anil Shrestha
  • Printing Support In Asp.Net Core
    TTMind Author
  • HOW TO EXTRACT TEXT FROM IMAGE USING JAVASCRIPT (OCR with Tesseract.js)?
    Prakash Pokhrel
  • Images Upload REST API using ASP.NET Core
    Prakash Pokhrel
  • Related Topic

  • How to read appSettings JSON from Class Library in ASP.NET Core
  • Printing Support In Asp.Net Core
  • Images Upload REST API using ASP.NET Core
  • How to use IActionFilter, IAsyncActionFilter in ASP.NET Core MVC?
  • ASP.NET CORE - Blazor CRUD operation using ADO.NET
  • Tech
  • About Us
  • Contact Us
  • TechHelp
  • PositiveHelp
  • Jim-Jams Help
  • Terms & Conditions

© Copyright ttmind.com

Main Content

Built-In Logging In .NET Core

.Net .Net Core about 8 years ago || 5/25/2018 || 3.1 K View

  • Hide

Introduction:

Logging is a process, which keeps trak of an application in order to keep it error-free and provide an environment for smooth functioning of the applicaiton. ASP.NET CORE provides us with built in logging system whenever its required so we don't need any third party logging.  It increases the  code efficiency and performance. 

Let us start by Creating a new ASP.NET Core Web application, name it, and select Web Application(MVC).

Step 1:  Install-Package Microsoft.Extensions.Logging

Add Logging

After the extension is installed, let us add  logging by adding ILogger(Custom Logging) or IloggerFactory on startup.cs. If we need to implement ILoggerFactory to use logging add logging services under ConfigureServices then we have to create it usign CreateLogger. Also we can use other loggings(like Nlog) with built-in logging which will requied minimal code.

services.AddLogging();

Startup.cs 

public class Startup {
 public Startup(IHostingEnvironment env) {
  var builder = new ConfigurationBuilder()
   .SetBasePath(env.ContentRootPath)
   .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
   .AddJsonFile($ "appsettings.{env.EnvironmentName}.json", optional: true)
   .AddEnvironmentVariables();
  Configuration = builder.Build();
 }

 public IConfigurationRoot Configuration {
  get;
 }

 // This method gets called by the runtime. Use this method to add services to the container.  
 public void ConfigureServices(IServiceCollection services) {
  // Add framework services.  
  services.AddMvc();
  services.AddLogging();
 }

 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
  loggerFactory.AddConsole(Configuration.GetSection("Logging"));
  loggerFactory.AddDebug();

  if (env.IsDevelopment()) {
   app.UseDeveloperExceptionPage();
   app.UseBrowserLink();
  } else {
   app.UseExceptionHandler("/Home/Error");
  }

  app.UseStaticFiles();

  app.UseMvc(routes => {
   routes.MapRoute(
    name: "default",
    template: "{controller=Home}/{action=Index}/{id?}");
  });
 }
}

 

ILoggerFactory: We can also use ILoggerFactory. For this, we must use CreateLogger. 

_logger = Mylogger.CreateLogger(typeof(HomeController));

HomeController.cs:

public class HomeController: Controller {
 private ILogger _logger;

 public HomeController(ILoggerFactory Mylogger) {
  _logger = Mylogger.CreateLogger(typeof(HomeController));
 }

 public IActionResult Index() {
  return View();
 }

 public IActionResult About() {
  try {
   ViewData["Message"] = "Your application description page.";
   _logger.LogInformation("About Page has been Accessed");
   return View();
  } catch (System.Exception ex) {
   _logger.LogError("About: " + ex.Message);
   throw;
  }
 }

 public IActionResult Contact() {
  try {
   ViewData["Message"] = "Your contact page.";
   _logger.LogInformation("Contact Page has been Accessed");
   return View();
  } catch (System.Exception ex) {
   _logger.LogError("Contact: " + ex.Message);
   throw;
  }
 }

 public IActionResult Error() {
  return View();
 }
}

Run and Test:

LogLevel: We can define logging level by providing the level we want in appsettings.json.

  • Trace
  • Debug
  • Information
  • Warning
  • Error
  • Application failure or crashes                   

Summary:
In similar fashion, we can use built-in logging frameworks and separate our application from logger implementation so that we can make the same framework reusable for other logging providers.

  • 0
  • 0
  • 0
    • Facebook
    • Twitter
    • Google +
    • LinkedIn

About author

Prakash Pokhrel

Prakash Pokhrel

https://np.linkedin.com/in/prakash-pokhrel-42a699a2

Reset Your Password
Enter your email address that you used to register. We'll send you an email with your username and a link to reset your password.

Quick Survey