Updated March 31, 2023
Introduction to ASP.NET Core Logging to File
ASP.NET Core Logging to File is essentially in any of the production applications; like that approach, we log the entire error in the Web Application. This way, the ASP.NET Core comes in a useful way where it offers maintains the output logs from the application. Logs are completed with the help of the middleware method, which makes the help of modular library design. Several libraries are included in the Web Application of ASP.NET Core, and a few are Third-Party extensions which installed through NuGet Package Manager.
ASP.NET Core Logging to File Overviews
Like the .NET Core logging mechanism, the ASP.NET Core reflects. The API Logger in Microsoft.Extensions.Logging works with various logging or built-in providers. In the ASP.NET Core application, we need to install the package called Microsoft.Extensions.Logging and also several logging providers of our preference.
How does ASP.NET Core Logging Works?
The ASP.NET Core contains the in-built logging framework, which is not enriched like third-party libraries. So we move on to one of the third-party called SeriLog. We can find the ILoggerFactory in the Configure Method of Startup class which contains in ASP.NET Core. We can see the start-up class while developing the new ASP.NET Core Web Application or API application.
Public void configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
}
Let’s see the following code of appsetting.json with their default settings as shown below,
{
"Logging":
{
"IncludeScopes": false,
"LogLevel":
{
// here the LogLevel applied to the entire enabled providers
"Default": "Information", // this was the default logging and error
"System": "Information",
"Microsoft": "Information"
}
}
}
Step by Step ASP.NET Core Logging to File
You can log a message, warnings, or error to a text file in three steps easily.
In ASP.NET Core Logging File, we can log a message, error, or warnings to a text file within three steps; they are as follows.
- In your project, add the SeriLog Extension Logging NuGet package.
- Call the method “AddFile” in the Startup Class
- In your Controller call the ILogger Information
Let’s see the following step by step procedures,
Initially to Include the SeriLog Extension to the Project
In the Solution Explorer, just right-click and manage the NuGet package and search for the SeriLog.Extension.Logging.File” and to install it.
Call the method “AddFile” method in the Startup class
The ILoggerFactory interface which offers the method called the AddFile repeatedly while installing the SeriLog Extension. In the method AddFile, we have to indicate the location to store the text file.
This is the file of appsettings.json with the default configuration as follows,
In Controller make a call on ILogger.
In this step have used the DI called the dependency Injection of ILogger<T> Logger service class, which stores the log errors as well as the log information.
Result of Testing’s
In the end, while executing the application, the log file will be created in the prescribed location; we can also set the location in the Startup Class Configure method. Let’s see the following image which describes it,
Add ASP.NET Core Logging Providers
In ASP.NET Core, we are required to include the providers in the LoggerFactory. In the application of ASP.NET Core MVC, call the WebHost.CreateDefaultBuilder(args) method in the SampleProgram.cs internally includes the EventSource , Debug and Console Logging providers.
Sample Program 1
public class SampleProgram
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
Sample Program 2
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging(logBuilder =>
{
logBuilder.ClearProviders(); // in LoggerFactory eliminate the entire providers
logBuilder.AddConsole();
logBuilder.AddTraceSource("Information, ActivityTracing"); //to include the trace Listener Provider
})
.UseStartup<Startup>();
The above code example contains the method ConfigureLogging() method, which captures action to <ILogBuilder> a delegate Action for the configuration of logging providers. To include logging providers of choice, exclude the default providers by using ClearProviders() and call extension method of provider to include like AddTraceSource() which add the provider of trace listener provider and the method AddConsole() method which includes Console Logging Provider. To configure the log provider by using ILoggerFactory in Configure() method of Startup class.
Create ASP.NET Core Logging to File
To create logs in the controller, we need to use ILoggerFactory or ILogger in the application using the ASP.NET Core Dependency Injection (DI); let’s see the following example from the HomeController.
Sample Code: Logging in Controller
namespace AspDotNetCoreMvcApp.Controllers
{
public class HomeController : Controller
{
private readonly ILogger _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
_logger.LogInformation("Messages of Logs in method Index()");
return View();
}
public IActionResult About()
{
_logger.LogInformation("Messages of Logs in method About()");
return View();
}
}
}
In the above sample code example, the parameter of ILogger<HomeController> which included in Constructor. The ASP.NET Core DI passes the ILogger instance used to log the action methods of Index () and About ().
To pass the HomeController as generic type for ILogger<HomeController> which will be used as category. By specifying the ILogger<HomeController> which displays the qualified name in logs called AspDotNetCoreMvpApp.Controller.HomeController in logs, let’s see the below line of code
info: AspDotNetCoreMvcApp.Controllers.HomeController[0]
The Log message in Index () method, the logged information using the method called LogInformation(), it starts with like “info:” with the qualified class name where the logs created: AspDotNetCoreMvcApp.Controllers.HomeController[0], here the event id is [0]. To specify the event id for identifying the record, for example: page number, Id, or any other information to identify a log uniquely. If we didn’t denote any event id, it assigns to 0, and the next line will be an actual log message like “Messages of Logs in method Index().”
We can achieve the same data bypassing the ILoggerFactroy in the constructor.
public class HomeController: Controller
{
private readonly ILogger _logger;
public HomeController(ILoggerFactory logFactory)
{
_logger = logFactory.CreateLogger<HomeController>();
}
public IActionResult Index()
{
_logger.LogInformation("Messages of Logs in method Index()");
return View();
}
public IActionResult About()
{
_logger.LogInformation("Messages of Logs in method About()");
return View();
}
}
Conclusion
This article explained the easy steps like logging the errors and warning to file by using third-party library SeriLog. I hope the article helps you to understand.
Recommended Articles
We hope that this EDUCBA information on “ASP.NET Core Logging to File” was beneficial to you. You can view EDUCBA’s recommended articles for more information.