Get started with IronPDF

Start using IronPDF in your project today with a free trial.

First Step:
green arrow pointer



Custom Logging Example

To utilize the custom logging feature, change the LoggingMode property to LoggingModes.Custom. Afterward, assign the CustomLogger property to the custom logger class that you have created.

:path=/static-assets/pdf/content-code-examples/how-to/custom-logging-custom-logging.cs
// This snippet configures the logging mode for IronSoftware's Logger
// and assigns a custom logger implementation.

// Set the logger to use a custom logging mode by assigning it to Custom.
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.Custom;

// Initialize a custom logger and assign it to the CustomLogger property.
// Here, an instance of CustomLoggerClass is created with "logging" as an argument.
IronSoftware.Logger.CustomLogger = new CustomLoggerClass("logging");

// Note: The CustomLoggerClass should be implemented elsewhere in your codebase.
// It is expected to conform to the logging requirements specified by IronSoftware's Logger,
// meaning it should implement the necessary interface or methods to correctly handle logging operations.
' This snippet configures the logging mode for IronSoftware's Logger

' and assigns a custom logger implementation.



' Set the logger to use a custom logging mode by assigning it to Custom.

IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.Custom



' Initialize a custom logger and assign it to the CustomLogger property.

' Here, an instance of CustomLoggerClass is created with "logging" as an argument.

IronSoftware.Logger.CustomLogger = New CustomLoggerClass("logging")



' Note: The CustomLoggerClass should be implemented elsewhere in your codebase.

' It is expected to conform to the logging requirements specified by IronSoftware's Logger,

' meaning it should implement the necessary interface or methods to correctly handle logging operations.
$vbLabelText   $csharpLabel

IronPdf logs will be directed to the custom logger object. The messages will remain identical to those in the IronPdf logger; they will simply be relayed to the custom logger. How the custom logger manages the messages will be determined by the custom logger designer. Let's use the following custom logger class as an example.

:path=/static-assets/pdf/content-code-examples/how-to/custom-logging-custom-logging-class.cs
using System;
using Microsoft.Extensions.Logging;

// CustomLoggerClass implements the ILogger interface to provide a custom logging mechanism.
public class CustomLoggerClass : ILogger
{
    // Private field to store the category name associated with the logger instance.
    private readonly string categoryName;

    // Constructor initializes the logger with a category name, typically to identify the source or context of the log message.
    public CustomLoggerClass(string categoryName)
    {
        this.categoryName = categoryName;
    }

    // BeginScope allows for scoped logging, but in this implementation, it does not perform any action and returns null.
    // This can be expanded in the future if needed.
    public IDisposable BeginScope<TState>(TState state)
    {
        return null; // No scope management implemented yet.
    }

    // Checks if a given log level is enabled for this logger.
    // This implementation always returns true, meaning all log levels are enabled.
    public bool IsEnabled(LogLevel logLevel)
    {
        return true; // Logging is always enabled for all levels in this simple logger.
    }

    // Logs a message at the specified log level, with additional details provided by eventId, state, and exception.
    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
    {
        if (formatter == null)
        {
            throw new ArgumentNullException(nameof(formatter)); // Throws exception if formatter is not provided.
        }

        // If the specified log level is not enabled, exit the method.
        if (!IsEnabled(logLevel))
        {
            return; // Short-circuiting if logging is not enabled.
        }

        // Use the formatter function to convert the state and exception into a log message.
        string logMessage = formatter(state, exception);

        // Write the composed log message to the console, including log level, category name, and the log message itself.
        Console.WriteLine($"[{DateTime.Now}] [{logLevel}] [{categoryName}] - {logMessage}");
    }
}
Imports System

Imports Microsoft.Extensions.Logging



' CustomLoggerClass implements the ILogger interface to provide a custom logging mechanism.

Public Class CustomLoggerClass

	Implements ILogger



	' Private field to store the category name associated with the logger instance.

	Private ReadOnly categoryName As String



	' Constructor initializes the logger with a category name, typically to identify the source or context of the log message.

	Public Sub New(ByVal categoryName As String)

		Me.categoryName = categoryName

	End Sub



	' BeginScope allows for scoped logging, but in this implementation, it does not perform any action and returns null.

	' This can be expanded in the future if needed.

	Public Function BeginScope(Of TState)(ByVal state As TState) As IDisposable

		Return Nothing ' No scope management implemented yet.

	End Function



	' Checks if a given log level is enabled for this logger.

	' This implementation always returns true, meaning all log levels are enabled.

	Public Function IsEnabled(ByVal logLevel As LogLevel) As Boolean

		Return True ' Logging is always enabled for all levels in this simple logger.

	End Function



	' Logs a message at the specified log level, with additional details provided by eventId, state, and exception.

	Public Sub Log(Of TState)(ByVal logLevel As LogLevel, ByVal eventId As EventId, ByVal state As TState, ByVal exception As Exception, ByVal formatter As Func(Of TState, Exception, String))

		If formatter Is Nothing Then

			Throw New ArgumentNullException(NameOf(formatter)) ' Throws exception if formatter is not provided.

		End If



		' If the specified log level is not enabled, exit the method.

		If Not IsEnabled(logLevel) Then

			Return ' Short-circuiting if logging is not enabled.

		End If



		' Use the formatter function to convert the state and exception into a log message.

		Dim logMessage As String = formatter(state, exception)



		' Write the composed log message to the console, including log level, category name, and the log message itself.

		Console.WriteLine($"[{DateTime.Now}] [{logLevel}] [{categoryName}] - {logMessage}")

	End Sub

End Class
$vbLabelText   $csharpLabel

In this case, I have prefixed the log messages with additional information.

Console window

Frequently Asked Questions

What is custom logging in C#?

Custom logging in C# refers to creating a logging system tailored to the specific needs of an application. It involves using log files to record information and events generated by the software during its operation.

How do I get started with custom logging?

To get started with custom logging using IronPDF, download IronPDF from NuGet, set the LoggingMode property to LoggingModes.Custom, assign your custom logger object to the CustomLogger property, and output the log messages to view the logs.

How do I set the logging mode to custom?

To set the logging mode to custom in IronPDF, assign the LoggingMode property of the ChromePdfRenderer instance to LoggingModes.Custom.

What is the purpose of the CustomLogger property?

The CustomLogger property in IronPDF is used to assign your custom logger object. This allows all log messages to be forwarded to the custom logger instead of the default IronPDF logger.

Can you provide an example of a custom logger class?

Yes, an example of a custom logger class involves implementing the ILogger interface from IronPDF and defining methods like LogInformation, LogWarning, and LogError, which can handle different types of log messages.

What interface must a custom logger implement?

A custom logger must implement the ILogger interface from IronPDF to ensure it can handle log messages appropriately.

How does custom logging enhance my application?

Custom logging enhances your application by providing tailored logging solutions that meet specific application requirements, improving monitoring, debugging, and maintenance.

What kind of log messages can a custom logger handle?

A custom logger can handle various log messages, including informational, warning, and error messages, allowing for comprehensive logging tailored to the application's needs.

Chaknith related to Custom Logging Example
Software Engineer
Chaknith is the Sherlock Holmes of developers. It first occurred to him he might have a future in software engineering, when he was doing code challenges for fun. His focus is on IronXL and IronBarcode, but he takes pride in helping customers with every product. Chaknith leverages his knowledge from talking directly with customers, to help further improve the products themselves. His anecdotal feedback goes beyond Jira tickets and supports product development, documentation and marketing, to improve customer’s overall experience.When he isn’t in the office, he can be found learning about machine learning, coding and hiking.