How do I implement logging in C#

Logging is an essential aspect of software development, allowing developers to track application behavior, diagnose issues, and monitor performance. In C#, logging can be implemented using various libraries, such as NLog, Serilog, or the built-in Microsoft.Extensions.Logging framework. Below is an example of how to use the Microsoft.Extensions.Logging framework in a simple console application.

using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; class Program { static void Main(string[] args) { // Set up dependency injection var serviceProvider = new ServiceCollection() .AddLogging(builder => builder .AddConsole() .AddDebug()) .BuildServiceProvider(); // Create a logger var logger = serviceProvider.GetService>(); // Example logging messages logger.LogInformation("Application has started"); logger.LogWarning("This is a warning message"); logger.LogError("An error occurred"); // Your application logic goes here logger.LogInformation("Application has ended"); } }

Logging C# Microsoft.Extensions.Logging Console Application Debug NLog Serilog