ASP.NET Core Logging to File
Before you get into this article, if you have not read the Logging here it is.
.NET Core supports a logging API that works with a variety of built-in and third-party logging providers. This article describes how to use logging API with built-in providers.
Introduction
ASP.NET core has inbuilt basic logging support automatically, yet has not the most customization features, and there is quite a number of third-party libraries that support the most elegant customization - built-in providers.
And in this article, we are going to explore one of the third-party libraries which is SeriLog
A short description about SeriLog
Serilog provides diagnostic logging to files, the console, and elsewhere. It is too easy to set up, easy API, and is portable between recent .NET platforms.
Unlike other logging libraries, Serilog is built with powerful structured event data in mind.
How ASP.NET Core Logging Works?
ASP.NET Core has an inbuilt logging framework that has not as feature-rich as third-party libraries. But before that, it is good to catch a before going to SeriLog third party.
ASP.NET Core has ILoggerFactory in the Startup class Configure method.
If you create a new ASP.NET Core Web application or ASP.NET Core Web API application you find as below start-up class.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
}
You may also find appsettings.json with default settings as below,
{
"Logging": {
"IncludeScopes": false,
"LogLevel": { // All providers, LogLevel applies to all the enabled providers.
"Default": "Information",// Default logging, Error and higher.
"System": "Information",
"Microsoft": "Information" // All Microsoft* categories, Warning and higher.
}
}
}
If you run your application, you get to see logs captured in the console.
Alright, until now we have a light view of ASP.NET Core logging basic technique.
However when you like to capture all logging errors, warnings, message to file (text file) - What would you do?
How quick that would be the implementation?
Yes - all questions and captured in a single word SeriLog Library
Logging to File?
You can log a message, warnings, or error to a text file in three steps easily.
STEP 1 Add SeriLog Extensions Logging NuGet package to your project
STEP 2 In Startup class call a method "AddFile"
STEP 3 Call ILogger Interface in your Controller
0 Comments