How to create a log file in web api

ASP.NET Core Logging to File

Introduction to ASP.NET Core Logging to File

ASP.NET Core Logging to File is essentially in any of your production applications; Like that approach, we log all the error in the web app. In this way, ASP.NET Core comes in handy when offering to maintain application output logs. The records are completed with the help of the middleware method, which makes the help of the modular library design. Several libraries are included in the ASP.NET Core web app, and some are third-party extensions that were installed via the NuGet Package Manager.

ASP.NET Core Logging to File Overviews

Like the .NET Core logging mechanism, ASP.NET Core reflects . The API logger in Microsoft.Extensions.Logging works with several built-in or logging providers. In the ASP.NET Core application, we need to install the package called Microsoft.Extensions.Logging and also several logging providers of our choice.

How does ASP.NET Core Logging work?

ASP.NET Core contains the built-in logging framework, which is not enriched like third-party libraries. So we turned to one of the third parties called SeriLog. We can find ILoggerFactory in the Configure Method of Startup class that contains ASP.NET Core. We can see the startup class while developing the new ASP.NET Core web app or API app.

Public void configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection(“Logging ” )); loggerFactory.AddDebug(); }

Let’s look at the following appsetting.json code with its default settings as follows,

{ “Logging”: { “IncludeScopes”: false, “LogLevel”: { // here the LogLevel applied to the all providers enabled “Default”: “Info”, // this was the default logging and error “System”: “Info”, “Microsoft”: “Info” } } }

See Also:  Help

ASP. NET Core for File

You can log a message, warning 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 in three steps; they are as follows.

  • In your project, add the SeriLog Extension Logging NuGet package.
  • Call the “AddFile” method on the startup class
  • In your controller call the ILogger information

Let’s see the following procedures step by step,

Initially to include the SeriLog extension to the project

In Solution Explorer, just right click and manage NuGet package and search for SeriLog.Extension.Logging.File” and install it.

ASP.NET Core Logging to File output 1

Call the “AddFile” method in the Startup class

The ILoggerFactory interface that offers the method called AddFile repeatedly during the SeriLog Extension installation. In the AddFile method, we must indicate the location to store the text file.

ASP.NET Core Logging to File output 2

This is the appsettings.json file with the default configuration as follows,

output 3

In the controller, make a call to ILogger.

In this Step, I used the DI called ILogger Logger Dependency Injection service class, which stores log errors as well as log information.

output 4

Results of the tests

At the end, while the application is running, the regi file stro will be created at the prescribed location; we can also set the location in the Configure Startup class method. Let’s see the following image that describes it,

output 5

Adding ASP.NET Core logging providers

In ASP.NET Core, we need to include the providers in LoggerFactory. In your ASP.NET Core MVC application, call the WebHost.CreateDefaultBuilder(args) method in SampleProgram.cs which internally includes the EventSource, Debug, and Console Logging providers.

See Also:  How To Brand Your Blog - Blog Branding 101

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(); }

Sample Program 2

public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureLogging(logBuilder => { logBuilder.ClearProviders(); // in LoggerFactory we remove all providers logBuilder.AddConsole();

The above code example contains the ConfigureLogging() method, which captures the action for a delegated action for configuring log providers.To include your log providers choice, exclude the default providers using ClearProviders() and the provider call extension method to include such as AddTraceSource() which adds the trace listener provider and the AddConsole() method which includes the console log provider To configure the log provider using ILoggerFactory in the Configure() method of the Startup class.

Create ASP.NET Core log to file

To create log s in the controller, we need to use ILoggerFactory or ILogger in the application using ASP.NET Core Dependency Injection (DI); Let’s look at the following example of the HomeController.

Sample code: Logging into the controller

namespace AspDotNetCoreMvcApp.Controllers { public class HomeController : Controller { private readonly ILogger _logger; public HomeController(ILogger logger) { _logger = logger; } Public IActionResult Index() { _logger.LogInformation(“Logs messages in the Index() method”); return View(); } public IActionResult About() { _logger.LogInformation(“Log messages in the About() method”); return View(); } } }

In the sample code example above, the ILogger parameter that is included in the Constructor. ASP.NET Core DI passes the ILogger instance used to register the Index() and About() action methods.

See Also:  Writing Your Own Resume Parser

To pass the HomeController as a generic type for ILogger to be used as the category . Specifying the ILogger that displays the qualified name in the logs named AspDotNetCoreMvpApp.Controller.HomeController in the logs, let’s look at the following line of code

info: AspDotNetCoreMvcApp.Controllers.HomeController[0]

The Log message in Index() method, the information logged using the method called LogInformation(), begins with “info:” with the qualified class name where the logs were created: AspDotNetCoreMvcApp.Controllers.HomeController[0 ] , here the event id is [0]. To specify the event id to identify the record, for example: page number, id, or any other information to uniquely identify a record. If we don’t give any event ID, it is set to 0 and the next line will be an actual log message like “Logs messages in Index() method”.

We can achieve the same data by omitting ILoggerFactroy in the constructor.

public class HomeController: Controller { private readonly ILogger _logger; public HomeController(ILoggerFactory logFactory) { _logger = logFactory.CreateLogger(); } Public IActionResult Index() { _logger.LogInformation(“Logs messages in the Index() method”); return View(); } public IActionResult About() { _logger.LogInformation(“Log messages in the About() method”); return View(); } }

Conclusion

This article explains the simple steps, how to log errors and warn the file using the third-party library SeriLog. I hope the article helps you understand.

Recommended Articles

We hope this information from EDUCBA on “ASP.NET Core Logging to File” will be of benefit to you. You can consult the articles recommended by EDUCBA for more information.

  1. Validation in ASP.NET
  2. ASP.NET Web Controls
  3. State Management ASP.NET Update Panel
  4. ASP.NET Update Panel

.

Leave a Reply

Your email address will not be published. Required fields are marked *