Microsoft Logging C# (How It Works For Developer)

Introduction

Logging is an essential technique in C# that captures information, warnings, errors, and other pertinent data while an application is running. It aids developers in keeping an eye on how their programs behave, troubleshooting problems, and comprehending how the application functions in various contexts. C# offers some logging frameworks and packages to make logging jobs easier. Microsoft.Extensions.Logging is among the most widely used logging frameworks in .NET Core applications. The Microsoft.Extensions.Logging NuGet package for .NET Core gives us access to several extension methods to help us write different log levels. In this article, we are going to see more about MS logging.

How to Set Up MS Logging

  1. Create a new Visual Studio project.
  2. Install the Microsoft.Extensions.Logging library from NuGet.
  3. Inject the Logger interface into the console.
  4. Configure the logging output.
  5. Write logs at different levels.
  6. Run the code.

Step 1: Create a new Visual Studio project

To get started, create a new project in Visual Studio.

Step 2: Install the Microsoft.Extensions.Logging library

Install the Microsoft.Extensions.Logging library using NuGet. This library provides the necessary classes and methods for logging in .NET Core applications.

Step 3: Inject the Logger interface into the console

To use the logging functionality, you need to inject an instance of the Logger interface into your console application. This can be done using a dependency injection framework or by manually creating an instance of the Logger class.

using Microsoft.Extensions.Logging;

// Inject the logger into the console
ILogger logger = LoggerFactory.Create(builder =>
{
    builder.AddConsole();
}).CreateLogger<Program>();
using Microsoft.Extensions.Logging;

// Inject the logger into the console
ILogger logger = LoggerFactory.Create(builder =>
{
    builder.AddConsole();
}).CreateLogger<Program>();
Imports Microsoft.Extensions.Logging

' Inject the logger into the console
Private logger As ILogger = LoggerFactory.Create(Sub(builder)
	builder.AddConsole()
End Sub).CreateLogger<Program>()
VB   C#

Step 4: Configure the logging output

Configure how the logs should be output. This can be done by adding one or more logging providers to the logger builder. The most common provider is the console logger, which outputs the logs to the console.

builder.AddConsole(options =>
{
    options.TimestampFormat = "[HH:mm:ss] ";
});
builder.AddConsole(options =>
{
    options.TimestampFormat = "[HH:mm:ss] ";
});
builder.AddConsole(Sub(options)
	options.TimestampFormat = "[HH:mm:ss] "
End Sub)
VB   C#

Step 5: Write logs at different levels

You can now write logs at different levels using the logger object. The logging methods available are LogDebug(), LogInformation(), LogWarning(), LogError(), and LogCritical().

logger.LogDebug("This is a debug message");
logger.LogInformation("This is an information message");
logger.LogWarning("This is a warning message");
logger.LogError("This is an error message");
logger.LogCritical("This is a critical message");
logger.LogDebug("This is a debug message");
logger.LogInformation("This is an information message");
logger.LogWarning("This is a warning message");
logger.LogError("This is an error message");
logger.LogCritical("This is a critical message");
logger.LogDebug("This is a debug message")
logger.LogInformation("This is an information message")
logger.LogWarning("This is a warning message")
logger.LogError("This is an error message")
logger.LogCritical("This is a critical message")
VB   C#

Step 6: Run the code

Finally, run your code and observe the logs being output according to the configured settings.

That's it! You have successfully set up and used MS logging in your C# application.

Install MS Logging

To install MS Logging, follow these steps:

  1. Launch Visual Studio.
  2. Navigate to Tools > NuGet Package Manager > Package Manager Console.
  3. In the Package Manager Console, execute the following command:

    Install-Package Microsoft.Extensions.Logging
  4. Press Enter to execute the command. This will download and install the Microsoft.Extensions.Logging package into your project.

Logging Levels

Several logging levels are available in the Microsoft.Extensions.Logging framework in C#, enabling developers to classify and rank log messages according to their significance and severity. These levels are frequently used to distinguish between various message types and assist in regulating the verbosity of logs.

The default logging levels offered by Microsoft.Extensions.Logging are as follows:

  • Trace: The most thorough level, often employed for incredibly detailed data that offers a deep level of understanding of the inner workings of the program.
  • Debug: Debugging information that is useful during the development and debugging stages but is often not required in a production setting.
  • Information: Offers details on how the application functions normally. Usually, the regular operation of the program is monitored using these logs.
  • Warning: Points to a possible problem or anything that may require attention in the future. It is used for anomalous or unexpected situations that could result in issues but don't necessarily cause the program to crash.
  • Error: Signals a serious problem or mistake that needs to be fixed immediately. Usually used to record issues that affect the application's operation.
  • Critical: The most severe state, used to record critical problems that need to be addressed immediately since they might cause serious issues or program crashes.

Each log level serves a specific purpose and provides developers with the ability to manage the amount of data the logging framework outputs. Developers can choose the appropriate level for message recording based on the severity and importance of the logged data.

Configuring C# Logging

Here is a basic example of how to configure logging using Microsoft.Extensions.Logging:

using Microsoft.Extensions.Logging;
using System;

class Program
{
    // Create a LoggerFactory instance
    private static readonly ILoggerFactory LoggerFactory = LoggerFactory.Create(builder =>
    {
        // Add console logger
        builder.AddConsole();
        // You can add other logging providers here (e.g., AddDebug, AddFile, etc.)
    });

    // Create a logger
    private static readonly ILogger Logger = LoggerFactory.CreateLogger<Program>();

    static void Main(string[] args)
    {
        // Example log messages
        Logger.LogInformation("Information log");
        Logger.LogWarning("Warning log");
        Logger.LogError("Error log");

        try
        {
            // Simulate an exception
            throw new Exception("Exception occurred");
        }
        catch (Exception ex)
        {
            // Log exception details
            Logger.LogError(ex, "Exception log");
        }

        Console.ReadKey();
    }
}
using Microsoft.Extensions.Logging;
using System;

class Program
{
    // Create a LoggerFactory instance
    private static readonly ILoggerFactory LoggerFactory = LoggerFactory.Create(builder =>
    {
        // Add console logger
        builder.AddConsole();
        // You can add other logging providers here (e.g., AddDebug, AddFile, etc.)
    });

    // Create a logger
    private static readonly ILogger Logger = LoggerFactory.CreateLogger<Program>();

    static void Main(string[] args)
    {
        // Example log messages
        Logger.LogInformation("Information log");
        Logger.LogWarning("Warning log");
        Logger.LogError("Error log");

        try
        {
            // Simulate an exception
            throw new Exception("Exception occurred");
        }
        catch (Exception ex)
        {
            // Log exception details
            Logger.LogError(ex, "Exception log");
        }

        Console.ReadKey();
    }
}
Imports Microsoft.Extensions.Logging
Imports System

Friend Class Program
	' Create a LoggerFactory instance
	Private Shared ReadOnly LoggerFactory As ILoggerFactory = LoggerFactory.Create(Sub(builder)
		' Add console logger
		builder.AddConsole()
		' You can add other logging providers here (e.g., AddDebug, AddFile, etc.)
	End Sub)

	' Create a logger
	Private Shared ReadOnly Logger As ILogger = LoggerFactory.CreateLogger(Of Program)()

	Shared Sub Main(ByVal args() As String)
		' Example log messages
		Logger.LogInformation("Information log")
		Logger.LogWarning("Warning log")
		Logger.LogError("Error log")

		Try
			' Simulate an exception
			Throw New Exception("Exception occurred")
		Catch ex As Exception
			' Log exception details
			Logger.LogError(ex, "Exception log")
		End Try

		Console.ReadKey()
	End Sub
End Class
VB   C#

In this example, a console logger is added to the logging configuration, which writes logs to the console. However, Microsoft.Extensions.Logging offers various logging providers, including logging to files, databases, or connecting with other logging frameworks. Additionally, it is possible to create custom logging providers that can format logs according to specific requirements.

Including Extra Providers for Logging

You can add additional logging sources by chaining the relevant methods within the Create() function. For example:

  • To add a debugger output logging provider, use builder.AddDebug().
  • To add a file logging provider, use builder.AddFile("log.txt").

MSLogging on IronPDF

To enable logging in IronPDF, you can use the Microsoft.Extensions.Logging framework along with IronPDF's built-in logging capabilities. Here's an example of how to set up logging in IronPDF:

using Microsoft.Extensions.Logging;
using IronPdf;

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

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

        // Enable logging in IronPDF
        Logger.Log = new LoggerImplementation(logger);

        // Use IronPDF and perform operations
        // ...

        // Example of logging an error in IronPDF
        Logger.Log.Error("An error occurred while processing the PDF");

        // Example of logging a warning in IronPDF
        Logger.Log.Warning("This is a warning message");

        // Example of logging an information message in IronPDF
        Logger.Log.Information("This is an information message");

        // ...

        // Close and dispose resources
        // ...

        // Flush the log messages
        loggerFactory.Dispose();
    }
}
using Microsoft.Extensions.Logging;
using IronPdf;

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

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

        // Enable logging in IronPDF
        Logger.Log = new LoggerImplementation(logger);

        // Use IronPDF and perform operations
        // ...

        // Example of logging an error in IronPDF
        Logger.Log.Error("An error occurred while processing the PDF");

        // Example of logging a warning in IronPDF
        Logger.Log.Warning("This is a warning message");

        // Example of logging an information message in IronPDF
        Logger.Log.Information("This is an information message");

        // ...

        // Close and dispose resources
        // ...

        // Flush the log messages
        loggerFactory.Dispose();
    }
}
Imports Microsoft.Extensions.Logging
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim loggerFactory As ILoggerFactory = LoggerFactory.Create(Sub(builder)
			builder.AddConsole().AddDebug()
		End Sub)

		Dim logger As ILogger(Of Program) = loggerFactory.CreateLogger(Of Program)()

		' Enable logging in IronPDF
		Logger.Log = New LoggerImplementation(logger)

		' Use IronPDF and perform operations
		' ...

		' Example of logging an error in IronPDF
		Logger.Log.Error("An error occurred while processing the PDF")

		' Example of logging a warning in IronPDF
		Logger.Log.Warning("This is a warning message")

		' Example of logging an information message in IronPDF
		Logger.Log.Information("This is an information message")

		' ...

		' Close and dispose resources
		' ...

		' Flush the log messages
		loggerFactory.Dispose()
	End Sub
End Class
VB   C#

In this example, we create an instance of the LoggerFactory from the Microsoft.Extensions.Logging framework. We then create a logger from the factory for the Program class.

To enable logging in IronPDF, we set the static Logger.Log property to an instance of LoggerImplementation that takes the logger from loggerFactory. With this configuration, you can use Logger.Log methods to log messages within IronPDF.

After performing the necessary operations with IronPDF, you can close and dispose resources, and then flush the log messages by disposing the loggerFactory.

Note: Ensure that you have the necessary dependencies and packages installed for Microsoft.Extensions.Logging and IronPDF.

Install IronPDF

To install the IronPDF library, follow these steps:

  1. Open the Package Manager Console in Visual Studio.
  2. Enter the following command to install the IronPDF library using NuGet:
Install-Package IronPdf

Alternatively, you can use the .NET CLI by running the following command in the terminal:

dotnet add package IronPdf
  1. Press Enter to execute the command. This will download and install the IronPDF package into your project.

It is also possible to install the IronPDF library using the NuGet Package Manager GUI. Simply search for the package "IronPDF" in the Browse tab, select the desired package from the list, and install the latest version of IronPDF.

Once the installation is complete, you can start using the IronPDF library in your project.

MS Logging using IronPDF

As of January 2022, IronPDF does not directly interact with Microsoft.Extensions.Logging and is not natively supported. IronPDF is primarily used as a tool for creating and modifying PDFs in C# programs.

However, you can still incorporate logging using Microsoft.Extensions. By integrating logging into your C# program alongside IronPDF, you can manage and log events related to PDF production, application workflow, or issues that occur when using IronPDF.

Here's an example of how to use Microsoft.Extensions to integrate logging with IronPDF:

using Microsoft.Extensions.Logging;
using IronPdf;
using System;

class Program
{
    private static readonly ILoggerFactory LoggerFactory = LoggerFactory.Create(builder =>
    {
        builder.AddConsole(); // Add other logging providers as needed
    });

    private static readonly ILogger Logger = LoggerFactory.CreateLogger<Program>();

    static void Main(string[] args)
    {
        try
        {
            // Your IronPDF code for PDF generation or manipulation
            var Renderer = new IronPdf.HtmlToPdf();
            var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");
            PDF.SaveAs("Output.pdf");
            Logger.LogInformation("PDF created successfully.");
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "An error occurred while generating the PDF.");
        }

        Console.ReadKey();
    }
}
using Microsoft.Extensions.Logging;
using IronPdf;
using System;

class Program
{
    private static readonly ILoggerFactory LoggerFactory = LoggerFactory.Create(builder =>
    {
        builder.AddConsole(); // Add other logging providers as needed
    });

    private static readonly ILogger Logger = LoggerFactory.CreateLogger<Program>();

    static void Main(string[] args)
    {
        try
        {
            // Your IronPDF code for PDF generation or manipulation
            var Renderer = new IronPdf.HtmlToPdf();
            var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");
            PDF.SaveAs("Output.pdf");
            Logger.LogInformation("PDF created successfully.");
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "An error occurred while generating the PDF.");
        }

        Console.ReadKey();
    }
}
Imports Microsoft.Extensions.Logging
Imports IronPdf
Imports System

Friend Class Program
	Private Shared ReadOnly LoggerFactory As ILoggerFactory = LoggerFactory.Create(Sub(builder)
		builder.AddConsole() ' Add other logging providers as needed
	End Sub)

	Private Shared ReadOnly Logger As ILogger = LoggerFactory.CreateLogger(Of Program)()

	Shared Sub Main(ByVal args() As String)
		Try
			' Your IronPDF code for PDF generation or manipulation
			Dim Renderer = New IronPdf.HtmlToPdf()
			Dim PDF = Renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>")
			PDF.SaveAs("Output.pdf")
			Logger.LogInformation("PDF created successfully.")
		Catch ex As Exception
			Logger.LogError(ex, "An error occurred while generating the PDF.")
		End Try

		Console.ReadKey()
	End Sub
End Class
VB   C#

This sample demonstrates a simple way to set up Microsoft.Extensions.Logging within a C# application that uses IronPDF. Logging messages are generated to document the successful creation of PDFs and to record any exceptions that may occur.

Make sure to customize the logging levels, error handling, and messages according to the specific needs of your application and the scenarios in which IronPDF is used for PDF creation or modification. Properly differentiating between different types of log messages using logging levels can be useful for effective debugging and monitoring.

To learn more about IronPDF, please visit the official website.

Conclusion

In conclusion, integrating Microsoft.Extensions.Logging allows C# developers to effectively handle logging tasks. IronPDF provides comprehensive logging capabilities, enabling thorough recording, analysis, and reporting of application events, failures, and vital data. This enhances application dependability, maintenance, and debugging.

IronPDF offers different software products, including a Lite bundle priced at $749. This bundle includes a permanent license, upgrade options, one year of software maintenance, and a thirty-day money-back guarantee. During the watermarked trial period, you can explore the features of IronPDF. To learn more about the software products offered by Iron Software, please visit their official website at https://ironsoftware.com/.