How to use Custom Logging in C#

Custom logging refers to the practice of implementing a logging system tailored to the specific needs and requirements of an application or system. It involves creating and using log files to record information, events, and messages generated by the software during its operation.

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
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.Custom;
IronSoftware.Logger.CustomLogger = new CustomLoggerClass("logging");
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.Custom
IronSoftware.Logger.CustomLogger = New CustomLoggerClass("logging")
$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
public class CustomLoggerClass : ILogger
{
    private readonly string categoryName;

    public CustomLoggerClass(string categoryName)
    {
        this.categoryName = categoryName;
    }

    public IDisposable BeginScope<TState>(TState state)
    {
        return null;
    }

    public bool IsEnabled(LogLevel logLevel)
    {
        return true;
    }

    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
    {
        if (!IsEnabled(logLevel))
        {
            return;
        }

        // Implement your custom logging logic here.
        string logMessage = formatter(state, exception);

        // You can use 'logLevel', 'eventId', 'categoryName', and 'logMessage' to log the message as needed.
        // For example, you can write it to a file, console, or another destination.

        // Example: Writing to the console
        Console.WriteLine($"[{logLevel}] [{categoryName}] - {logMessage}");
    }
}
Public Class CustomLoggerClass
	Implements ILogger

	Private ReadOnly categoryName As String

	Public Sub New(ByVal categoryName As String)
		Me.categoryName = categoryName
	End Sub

	Public Function BeginScope(Of TState)(ByVal state As TState) As IDisposable
		Return Nothing
	End Function

	Public Function IsEnabled(ByVal logLevel As LogLevel) As Boolean
		Return True
	End Function

	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 Not IsEnabled(logLevel) Then
			Return
		End If

		' Implement your custom logging logic here.
		Dim logMessage As String = formatter(state, exception)

		' You can use 'logLevel', 'eventId', 'categoryName', and 'logMessage' to log the message as needed.
		' For example, you can write it to a file, console, or another destination.

		' Example: Writing to the console
		Console.WriteLine($"[{logLevel}] [{categoryName}] - {logMessage}")
	End Sub
End Class
$vbLabelText   $csharpLabel

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

Console window

Ready to see what else you can do? Check out our tutorial page here: Addtional Features

Frequently Asked Questions

How can I implement custom logging in C#?

You can implement custom logging in C# by using IronPDF. First, download IronPDF from NuGet, then set the LoggingMode property to LoggingModes.Custom, and assign your custom logger object to the CustomLogger property. This setup ensures all log messages are directed to your custom logger.

What steps are needed to start custom logging with IronPDF?

To start custom logging with IronPDF, download the library from NuGet, set the LoggingMode to LoggingModes.Custom, assign a custom logger to the CustomLogger property, and ensure all log messages are forwarded to your logger for output.

What is the role of the CustomLogger property in IronPDF?

The CustomLogger property in IronPDF allows you to assign a custom logger object. This feature forwards all log messages to the custom logger, enabling you to manage how logs are recorded and displayed according to your application's needs.

Can you provide a detailed example of setting up a custom logger in C#?

Certainly! To set up a custom logger in C#, you need to implement the ILogger interface from IronPDF. Define methods like LogInformation, LogWarning, and LogError to handle various log messages, then assign your custom logger to the CustomLogger property.

Why should I use custom logging in my C# application?

Custom logging is beneficial in a C# application as it allows you to create a logging system that meets your specific needs. This customization enhances monitoring, debugging, and maintenance by providing detailed and relevant log information.

What are the benefits of using custom logging with IronPDF?

Using custom logging with IronPDF provides flexibility in how log messages are managed. It allows you to tailor logging to suit your application's requirements, ensuring that you capture and handle log messages in the most effective way for your processes.

How does the ILogger interface support custom logging?

The ILogger interface supports custom logging by providing a structure that you must implement in your custom logger. It includes methods for handling different log message types, ensuring comprehensive logging capabilities.

What types of messages can be logged using a custom logger in IronPDF?

A custom logger in IronPDF can handle a variety of log messages, including informational, warning, and error messages. This comprehensive logging capability ensures that you have detailed records of your application's operations.

Chaknith Bin
Software Engineer
Chaknith works on IronXL and IronBarcode. He has deep expertise in C# and .NET, helping improve the software and support customers. His insights from user interactions contribute to better products, documentation, and overall experience.