IRONSOFTWAREHOME
.NET HELP

Microsoft Logging C# (How It Works For Developers)

Jacob Mellor, Chief Technology Officer @ Team Iron
Jacob Mellor
Updated: July 5, 2026

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 the Microsoft.Extensions.Logging package page on 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 the Microsoft.Extensions.Logging package page on 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 ILogger interface into your console application. This can be done by using a logging factory.

using Microsoft.Extensions.Logging;

// Create a logger for the application
ILogger<Program> logger = LoggerFactory.Create(builder =>
{
    builder.AddConsole(); // Adding console logging
}).CreateLogger<Program>();

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] "; // Setting the timestamp format for logs
});

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");

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
    PowerShell
  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(); // Wait for a key press before closing the application
    }
}

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

IronPDF excels in HTML to PDF conversion, ensuring precise preservation of original layouts and styles. It's perfect for creating PDFs from web-based content such as reports, invoices, and documentation. With support for HTML files, URLs, and raw HTML strings, IronPDF easily produces high-quality PDF documents.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}

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

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 of resources, and then flush the log messages by disposing of 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:

PM > Install-Package IronPdf

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

PM > Install-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(); // Wait for a key press before closing the application
    }
}

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 IronPDF homepage,.

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 $999. 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 Iron Software's official website.

Jacob Mellor, Chief Technology Officer @ Team Iron
Chief Technology Officer

Jacob Mellor is Chief Technology Officer at Iron Software and a visionary engineer pioneering C# PDF technology. As the original developer behind Iron Software's core codebase, he has shaped the company's product architecture since its inception, transforming it alongside CEO Cameron Rimington into a 50+ person company serving NASA, Tesla, and global government agencies.

...
Read More

Related Articles

Key in blue circle

Get your free 30-day Trial Key instantly.

Your trial license will be sent to your email address

No limitations. 100% unlocked. No credit card.

OR
bullet_checkedNo credit card or account creation requiredNo limitations. 100% unlocked. No credit card.
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
Book your free Live Demo
Booking Badge

Trusted by Millions of Engineers Worldwide

Iron Software's customer logos
Get Your No-Obligation Consult
Complete the form below or email sales@ironsoftware.com
Your details will always be kept confidential.
Trusted by Millions of Engineers Worldwide
Iron Software's customer logos
Get your free 30-day Trial Key instantly.
No credit card or account creation required
C# NuGet Library for PDF
Install with NuGet

Version: 2026.9

PM > Install-Package IronPdf
nuget.org/packages/IronPdf/
  1. In Solution Explorer, right-click References, Manage NuGet Packages
  2. Select Browse and search "IronPdf"
  3. Select the package and install
C# PDF DLL
Download DLL

Version: 2026.9

or download Windows Installer here.

  1. Download and unzip IronPDF to a location such as ~/Libs within your Solution directory
  2. In Visual Studio Solution Explorer, right click References. Select Browse, "IronPdf.dll"

Licenses from $999