Using Log4Net for Logging in WPF/Desktop Application

Using Log4Net for Logging in WPFWindows Presentation Foundation Application

Today in this article, we will see how to perform logging using Log4Net in WPF(Windows Presentation Foundation) .NET Core application.

Today in this article, we will cover below aspects,

As we understood .NET Core only provides basic providers for logging purposes like Console, EventSource, etc. File logging providers like File or RollingFile is still not available through the .NET Core framework.

Microsoft recommends using a third-party logger framework like a Serlilog or Log4Net or NLog for high-end logging requirements like Database or File/Rolling File logging.

So here we need to rely on external solutions and today we shall see how to use Log4Net addressing the same requirement of File/Rolling File Logging or Console logging in the WPF(Windows Presentation Foundation)  app.

We shall be leveraging DI( Dependency Injection) framework to inject the Log4Net Logger object into the mini IoC DI container in a .NET Core Console application.

Using Log4NET, logging can be done on Console or File or Rolling file easily. Log4NET also provides flexibility to control log layout and log as per log level types in the application.

Getting Started

Here I am using a WPF App (.NET Core) application template.

Using Log4Net for Logging in WPFWindows Presentation Foundation Application

Creating Generic HostBuilder

We will be leveraging DI( Dependency Injection) framework to inject the Log4Net Logger.

The HostBuilder class is available from the following namespace,

using Microsoft.Extensions.Hosting;

Please install the NuGet package from Nuget Package manager or PMC,

PM> Install-Package Microsoft.Extensions.Hosting -Version 3.1.1

Configuring Log4Net in WPF App

Log4Net is available through the NuGet packages manager.

PM> Install-Package Microsoft.Extensions.Logging.Log4Net.AspNetCore -Version 3.1.0

Or

Please install the package through Nuget Package Manager,

Using Log4Net for Logging in WPFWindows Presentation Foundation Application

Please create Generic HosBuilder and register the dependencies like Log4Net and other business dependencies.

See below implementation for HostBuilder and registration for Log4Net logging.

I have master Windows called ‘EmployeeWindowwhich can be registered as a singleton instance in the IoC container.

These changes can be done in the Application‘s constructor,

          IHost host = new HostBuilder()
            .ConfigureServices((hostContext, services) =>
            {
                //Lets Create single tone instance of Master windows
              services.AddSingleton<EmployeeWindow>();
           });

Next step is to register Log4Net in IoC container as below,

           host = new HostBuilder()
           .ConfigureServices((hostContext, services) =>
           {
               //Lets Create single tone instance of Master windows
               services.AddSingleton<EmployeeWindow>();

           }).ConfigureLogging(logBuilder =>
           {
               logBuilder.SetMinimumLevel(LogLevel.Trace);
               logBuilder.AddLog4Net("log4net.config");

           }).Build();

Please add a new Log4Net.config file if not available,

Using Log4Net for Logging in WPFWindows Presentation Foundation Application

This file needs to be updated with log layout details and configuration as given below as an example.

Below is the complete implementation for IoC container implementation which you need to add to the App() constructor method.

All set, Lets now define and do dependency injection of ILogger instance within Application Class as below,

Using Log4Net for Logging in WPFWindows Presentation Foundation Application

The log file shall be created in the project output directory unless specified with a custom path.

Below shows an example of file logging created by Log4Net,

File Logging using File Appender in WPF

If you wish to enable only File/Rolling File logging appender, please use the File appender in the log4net.config file as shown in the below example.

Please make sure to add appender reference in the config file as ref=”RollingFile” in the config file.

Sample log4net.config file for file appender is as below,

<log4net>
  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <file value="TheCodeBuzz.log" />
    <appendToFile value="true" />
    <maximumFileSize value="100KB" />
    <maxSizeRollBackups value="2" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
    </layout>
  </appender>
  <root>
    <level value="TRACE" />
    <appender-ref ref="RollingFile" />
  </root>
</log4net>

Logging using Console Appender in WPF

Below is sample log4net.config for the Console appender as below. Please make sure to add appender reference in the config file as,

<appender-ref ref="ConsoleAppender" />

Here is Example,

<appender name="Console" type="log4net.Appender.ConsoleAppender">
    <layout type="log4net.Layout.PatternLayout">
      <!-- Pattern to output the caller's file name and line number -->
      <conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
    </layout>
  </appender>

    <appender-ref ref="ConsoleAppender" />
  </root>

Log4NeT also supports multiple appenders configured at a time.

References: Dependency Injection in WPF in .NET Core

Please let me know if you have any questions or suggestions. Please sound off your comments below.

Happy Coding !!

Summary

Today in this article we saw how to use Log4Net logging in a .NET Core WPF application. Logging in .NET Core is simplified further and using Log4Net helps us enabling logging in a few simple steps and addresses the high-end logging requirement file-based and other types of logging requirements easily.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *