Gain Control of your .NET Logging Using log4net

Gain Control of your .NET Logging Using log4net

have always considered logging a critical function of any production application; however, it’s often overlooked. Logging is often added to the application only after the functionality is already defined and sometimes even after the application has been completely developed.

Many frameworks implement easy and flexible logging functionality in your applications. One of the best-known frameworks for .NET is log4net. This framework is based on the popular “log4j” framework, which was originally developed for Java applications. Log4net is characterized by extremely flexible XML file configuration, a variety of log targets and output formatting options. And of course it comes with full source code.

Starting log4net
I’m not going to go through setup procedure for log4net; instead, I’ll just give you some pointers so you’ll be able to start logging quickly. For those of you just starting to use the framework, the log4net documentation is excellent.

Here are the basic steps to set up logging in your application:

  1. Create an XML configuration file for the log4net framework to use. This configuration file specifies logger sections, appenders, and the relationships between the two.
  2. Load the configuration file using the following code:
  3.    [assembly : log4net.Config.XmlConfigurator(      Watch=true)]
  4. Create a log variable that you will use to write log entries.
  5. Use the methods [logvariable].Log(), .Warn(), .Error() or other available methods to write log entries.

XML Configuration files
You can store configuration information in a separate configuration file or as a part of your project’s app.config file and is the simplest way to set up log4net logging parameters. It’s worth mentioning that anything you can set up via configuration files in log4net can be accomplished through code as well. However, XML configuration files support automatic reloading which can be extremely useful for changing the log configuration while the program is already executing, for example to temporarily enable debug output. For more information about log4net configuration see this section of the log4net documentation.

It’s worth mentioning that anything you can set up in log4net via configuration files can be accomplished through code as well.

You must define two main elements in the configuration file: loggers and appenders. Loggers specify classes/namespace hierarchies to be logged, while appenders specify the location to which log4net will log entries. Appenders are destinations that will be used for displaying or storing log entries.

Here’s a basic configuration section:

   <>     <
> <> <> <> <> <> <> <> <> <> <> <> <> <> <> <> <>

The system logs entries from the most specific to the most general; in other words, specific loggers will be used when the namespace and class name of the class to be logged are specified explicitly in the configuration. If no match is found, the system applies the root logger and its specified appender, which is the console in the preceding configuration example.

Initializing and Using Log4net
You need only two simple steps to initialize and use log4net:

  1. Add an assembly-level attribute to the executing assembly as shown below:
  2.    [assembly : log4net.Config.XmlConfigurator(Watch=true)]

    The preceding attribute causes the log4net framework to load the XML configuration from the app.config file and monitor the file for any configuration changes. You can also use the XmlConfigurator class to load and watch configuration files by calling the Configure() and ConfigureAndWatch() methods directly.

  3. Next, create a static variable that you’ll use to call log4net framework, and use the default LogManager to initialize it to the default Logger implementation
       private static readonly ILog log = LogManager.GetLogger(      System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

You should declare a static variable in each class for logging information; you should not share the variable across classes. However, by bending that rule and knowing that logger properties are initialized at the point of variable declaration, it is possible to create multiple logger instances initialized to different values.

To send a string for logging, use the Debug(), Info(), Error() or other methods available through your declared variable from the ILog interface.

You should declare a static variable in each class for logging information; you should not share the variable across classes.

Custom Appenders: Adding Destinations
One common customization is creating a custom appender that logs messages to a proprietary destination, such as an MSMQ queue, a database table, etc. Log4net makes it extremely easy to create custom appenders. A custom appender class must implement the IAppender interface. The easiest (and recommended) way is to create a class that inherits from the log4net.Appender.AppenderSkeleton class, and implement the required function void Append(LoggingEvent loggingEvent). What you do within the loggingEvent method is entirely up to you, based on the needs of your custom appender. For example, here’s a custom appender that simply shows a MessageBox:

   protected override void Append(LoggingEvent loggingEvent)   {      MessageBox.Show(RenderLoggingEvent(loggingEvent));   }

A couple of things you should remember:

  • Appenders are called in the order in which you define them in the configuration file.
  • Calls to appenders are synchronous and therefore you should optimize custom appenders for speed.

The log4net framework loads appenders using reflection because that makes it possible to reference classes that exist in both the executing assembly and in different assemblies by specifying full assembly reference in the configuration element.

Custom Loggers: Adding Message Attributes
Another more advanced customization is required to implement a custom logging interface to allow adding of additional attributes or tags to each message logged. A possible scenario is an application component that’s required to provide a CustomerId in with a logging call. This requires extending ILog interface, a custom Logger, and a custom LogManager that will create an instance of the logger. All three tasks are very straight forward.

I’ve based this example on the log4net documentation for a template (see the downloadable code for this article). Look at log4netextensions
et1.0log4net.Ext.EventIDcssrc
for the custom logger extension code.

Start by creating a public interface named ICustomLog that inherits from ILog. Add the definitions for the Debug(), Info(), Warn(), Error(), and Fatal() methods by using the following signatures

   void Debug(stringCustomerId, object message);   void Debug(stringCustomerId, object message, Exception t);

Next, using the EventIDLogImpl.cs sample file as a base, implement a CustomLogImpl class. In this class, declare a static variable called ThisDeclaringType as follows:

   private readonly static Type ThisDeclaringType =       typeof(CustomLogImpl);

Then implement the ICustomLog member methods using the following template

   public void Debug(string CustomerId, object message)   {      Debug(CustomerId, message, null);   }      public void Debug(string CustomerId, object message, Exception t)   {      if (this.IsDebugEnabled)      {         LoggingEvent loggingEvent = new             LoggingEvent(ThisDeclaringType, Logger.Repository,             Logger.Name, Level.Debug, message, t);         loggingEvent.Properties["CustomerId"] = CustomerId;         Logger.Log(loggingEvent);      }   }

Change this.IsDebugEnabled and Level.Debug to the appropriate values for the other functions.

The last class you’ll need to implement is a CustomLogManager. Because the implementation is not exactly straightforward, I recommend that you make a copy of the EventIDLogManager class from the sample directory, and then run a search-and-replace command, changing “EventID” to “Custom.” The code below illustrates the type (although not the full extent) of the required changes.

      public class EventIDLogManager      {            #region Constructor            ///          /// Private constructor to prevent object creation         ///          private EventIDLogManager() { }            #endregion         // Becomes...         public class CustomLogManager      {            #region Constructor            ///          /// Private constructor to prevent object creation         ///          private CustomLogManager() { }            #endregion      

Using a custom logger is as easy as using the original logger that comes with log4net. The only real difference is that you declare a log variable of the CustomLogManager type and use ICustomLog interfaces, for example:

   private static readonly ICustomLog log =       CustomLogManager.GetLogger(      System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

A number of logging frameworks exist on the market, some with commercial backing, and some with open source origins. Log4net is an extremely powerful logging framework that has been proven time and time again in large production environments. It is highly scalable, extensible, and it’s a logging option that makes it possible to easily implement flexible and reliable logging in all your applications.

devx-admin

devx-admin

Share the Post:
Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023,

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed

Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at the Lubiatowo-Kopalino site in Pomerania.

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will result in job losses. However,

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023, more than one-fifth of automobiles

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed are at the forefront because

Sunsets' Technique

Inside the Climate Battle: Make Sunsets’ Technique

On February 12, 2023, Luke Iseman and Andrew Song from the solar geoengineering firm Make Sunsets showcased their technique for injecting sulfur dioxide (SO₂) into the stratosphere as a means

AI Adherence Prediction

AI Algorithm Predicts Treatment Adherence

Swoop, a prominent consumer health data company, has unveiled a cutting-edge algorithm capable of predicting adherence to treatment in people with Multiple Sclerosis (MS) and other health conditions. Utilizing artificial

Personalized UX

Here’s Why You Need to Use JavaScript and Cookies

In today’s increasingly digital world, websites often rely on JavaScript and cookies to provide users with a more seamless and personalized browsing experience. These key components allow websites to display

Geoengineering Methods

Scientists Dimming the Sun: It’s a Good Thing

Scientists at the University of Bern have been exploring geoengineering methods that could potentially slow down the melting of the West Antarctic ice sheet by reducing sunlight exposure. Among these

why startups succeed

The Top Reasons Why Startups Succeed

Everyone hears the stories. Apple was started in a garage. Musk slept in a rented office space while he was creating PayPal with his brother. Facebook was coded by a

Bold Evolution

Intel’s Bold Comeback

Intel, a leading figure in the semiconductor industry, has underperformed in the stock market over the past five years, with shares dropping by 4% as opposed to the 176% return

Semiconductor market

Semiconductor Slump: Rebound on the Horizon

In recent years, the semiconductor sector has faced a slump due to decreasing PC and smartphone sales, especially in 2022 and 2023. Nonetheless, as 2024 approaches, the industry seems to

Elevated Content Deals

Elevate Your Content Creation with Amazing Deals

The latest Tech Deals cater to creators of different levels and budgets, featuring a variety of computer accessories and tools designed specifically for content creation. Enhance your technological setup with

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security. These carefully designed learning courses

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers to better manage smaller unmanned

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like artificial intelligence (AI), semiconductors, and

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20 percent, which matches the lowest

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private, and SaaS applications. The suite

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have already been acquired by clients.

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications, it suffers from certain limitations.

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure. The company has decided to

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones beyond the visual line of

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company. With a previous valuation of

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service Providers (MSPs) increased control and

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for this limitation remains uncertain, specialists