Logging
Logging is an essential part of software development. It provides developers and support teams with special 'glasses' which enable them to see what the application code is really doing.
Prior to .NET Core, we used to inject a logger into the classes and we needed to introduce a dependency on a 3rd party library . In .NET Core, you don’t have a dependency on a 3rd party library’s namespace – just a namespace provided by Microsoft. By default Asp.net Core has option debug to Console, EventSource.
What is Serilog
Serilog is a logging framework for logging structured data. This framework is built around the idea that log messages should be more than a collection of strings. Log messages are preserved as structured data(JSON) that can be written in document form to a variety of output providers. (https://serilog.net/)
Steps to integrate Serilog in ASP.NET Core using Visual Studio Code.
Install the following,
For the demo purpose I have used Web Application.
Step1 : Create a web app with dotnet
- mkdir DemoSeriLog
- cd DemoSeriLog
- dotnet new mvc
Open the DemoSeriLog folder in Visual Studio Code (VS Code) and select the Startup.cs file.
- Select Yes to the Warn message "Required assets to build and debug are missing from DemoGoogleChart . Add them?"
- Select Restore to the Info message "There are unresolved dependencies".
Step 2
Install NuGet Package Manager extension. After you've installed it, to add a package, press Ctrl+P, type > nuget and press Enter.
- Then, select "NuGet Package Manager:Add Package"
- Enter package name : Serilog
- Select package name and version
Step 3
Follow the same procedure to add “Serilog.Extensions.Logging.File” as in Step1.
Step4
In the Startup.cs, add the below code line in Configure method and increase the parameter in Configure method.
- public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
- loggerFactory.AddFile("Logs/myapp-{Date}.txt);
Step5
Go to HomeController and add dependency using constructor. Update the Constructor to Inject ILogger interface implementor.
- public class HomeController: Controller {
- private readonly ILogger _logger;
- public HomeController(ILogger < HomeController > logger) {
- _logger = logger;
- }
Step6
Calling logging method in i.e. LogInformation
- public IActionResult Index()
- {
- _logger.LogInformation("Demo Logging Information in Index Method");
- return View();
- }
Step7
Logs will be written into a file system.
That’s it. Thanks for reading.