Boosting Code Quality with Effective Logging in C#

Introduction

A Crucial component of software development is LOGGING. It supports developers in problem detection, issue resolution & application behavior monitoring.

1. System.Diagnostics

System. Diagnostics, a potent logging library offered by the .NET Framework in C#, Is just one of the several 3rd party libraries that are available to make logging even more effective and diverse.

In this article, we'll examine various logging methods in C# and offer code samples that show how to use them.

using System;
using System.Diagnostics;

class Program
{
    static void Main()
    {
        Trace.Listeners.Add(new TextWriterTraceListener("log.txt"));
        Trace.AutoFlush = true;
        
        Trace.WriteLine("This is a trace message");
        Debug.WriteLine("This is a debug message");
        
        Console.WriteLine("Log messages have been written.");
    }
}

A TextWriteTraceListener that sends a log message to a text file was discussed in this example. You can log in to the console or other places as well.

2) Using 3rd Party Logging Frameworks (Serilog)

It offers a customizable and extensible method for logging messages. Install the Serilog NuGet Package first to get going.

Install-Package Serilog

Sample example of using Serilog to log messages.

using Serilog;

class Program
{
    static void Main()
    {
        Log.Logger = new LoggerConfiguration()
            .WriteTo.File("log.txt")
            .CreateLogger();
        
        Log.Information("This is an information message");
        Log.Error("This is an error message");
        
        Log.CloseAndFlush();
    }
}

3) Logging with Microsoft.Extensions.Logging

Using Microsoft.Extensions.Logging is the built-in logging system offered by Microsoft. Extensions are useful if you're working on ASP.NET Core Applications. It provides a powerful and adaptable method for message logging. Here's how you can use it.

using Microsoft.Extensions.Logging;

class Program
{
    static void Main()
    {
        ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
        {
            builder.AddConsole();
            builder.AddDebug();
        });

        ILogger logger = loggerFactory.CreateLogger<Program>();

        logger.LogInformation("This is an information message");
        logger.LogError("This is an error message");
    }
}

4) Log4Net

 Another Popular logging library in the .Net ecosystem. Install this package with the help of the Install-Package log4net.

Install-Package log4net

Sample Code

using log4net;
using log4net.Config;

class Program
{
    private static readonly ILog log = LogManager.GetLogger(typeof(Program));

    static void Main()
    {
        BasicConfigurator.Configure();

        log.Info("This is an information message");
        log.Error("This is an error message");
    }
}

Log4net Provides numerous options for tailoring log messages and logging to multiple outputs.

Conclusion

In C#, logging is a key component of program development. Regardless of whether you select the integrated Microsoft.Extensions, the built-in System.Diagnostics namespace, or a third-party library like Serilog or Log4net. It's crucial to implement good logging standards into your applications while using ASP.NET Core. You can monitor the performance of your application in Production and troubleshoot bugs with the assistance of effective logging. Select the logging framework that best satisfies the needs of the project, and begin effective logging today.


Similar Articles