Built-In Logging In .NET Core
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.