How-to: Set up log4net on a new project

Today I want to talk about adding log4net to a new project. It’s not hugely complicated or high-tech, but there are a few factors that mean I always seem to struggle with one aspect or another. There’s usually an irritating couple of minutes when I’m Googling questions and seeing purple links! This post is a sort of memo to myself then, and perhaps next time this post will be among those Google results!

Why is it hard?

Just here for the guide on how to set up log4net on a new project? Feel free to skip this bit and go directly to the step-by-step below.

First off, I found it quite interesting to consider why this is such a mental block for me. I think it comes down to 3 main reasons:

  1. It’s not something I do often. I don’t start new projects more than, say, once every couple of months. Moreover, once you’ve added log4net to a project, you don’t need to do it again. Performing a task this infrequently means that (for me at least) I don’t remember each step accurately.
  2. There’s more than one way of doing it. As detailed below, you can make decisions about how to do certain steps. The trick is to remember that some choices have consequences.
  3. There’s very little feedback. I think this is by design – I mean, once your logging system is configured correctly, you kind of want it to just fade away into the background, right? A shouty logger sounds pretty annoying to me. While you can turn on a debugging mode (see step 6), this only kicks in once you’ve managed to invoke log4net in the first place. The problem is (and, again, I get that it’s a trade-off) is that trying to log when log4net hasn’t been initialised at all just fails silently.

This sort of reflection is important for us software developers to consider. For a couple of reasons actually. Firstly, evaluating what sort of thing we find difficult to grasp tells us what sort of learner we are. Once we’ve identified this, we can adapt our approach to learning. Case in point: I’ve realised that doing something so infrequently means it won’t stick, so I’m writing a blog post.

The second reason reflecting on this is important is that evaluating software written by others (log4net is, after all, just more software) can help us to design and built better software ourselves. By identifying its strengths and weaknesses, we can consciously choose to emulate or deviate from these in our own practice. For instance, would I design software that fails silently?

Step-by-step

OK, so now we’re done with all the contemplation, let’s get on with it.

1. Getting the package

First things first: you’ll want to get the log4net NuGet package added to your project. It’s called “log4net” – you can’t miss it!

2. Write the configuration file

Next, you’ll need to specify how you’d like log4net to behave. To do this you’ll need to write some XML. Here’s an example from a recent project:

Normally, the bit of this that you’ll probably be most interested in will be the appender(s). These specify to where your logs will be written. In the sample above, I have two: one that outputs to the console and one that writes to a file (specifically a “rolling file appender”, but let’s not get bogged down).

To connect my logging activity to these appenders, I reference them in the “root” element. It is also possible to specify different “loggers”, each with their own threshold and appenders. For a full guide to what you can put in here, see the configuration section in the manual.

Now, we have to make a decision: do we want to place this configuration in its own file (called, for instance, “log4net.config”), or do we want to include it as a section in our “app.config”? The latter makes sense for small configurations, whereas I find larger configurations easier to manage in their own file. If you’re go down the “app.config” route, you’ll just need to make sure you include a section definition too (you may already have the parent element, particularly if you’re using Entity Frameworks):

If you’re using a dedicated config file, you’ll also need to wrap your config in the usual top and tail:

3. Loading your config file

Now that you’ve written (or pasted) your shiny new configuration, you’ll need to tell your application to actually use it. There are two ways to do this: either in your “AssemblyInfo.cs” file, or with a call at the root of your application. The former is preferable (in my most humble opinion), as it’s “set and forget” – it’s very unlikely that you (or your collaborators) will go poking around and accidentally delete your call. On the other hand, a configuration specified in “app.config” can’t be loaded from “AssemblyInfo.cs”, so you’ll have to do it from your application root.

If you do opt for the “AssemblyInfo.cs” route, you’ll just need to add something like the below:

If you choose (or need) to load your config in your application root, the first step is to determine where this should be. What you want is a place where we can be confident that our call will be hit early in the execution for all paths through our app. One example would be within the entry point ( static void Main(string[] args) ) of a console application. Once you’ve established the correct location, you’ll want to include the following:

4. Creating a logger to use in your code

We’re so nearly there! The last step before we start logging is to fetch a logger object from log4net’s “LogManager”. We have the option to specify a name for this logger, but the convention is to use the name of the calling class.

5. Let’s start logging!

Now that we’ve laid the groundwork, we can start logging. Assuming that we’ve got a logger called “Log”, as in the above example, we can start logging like this:

These last steps (4 & 5) are really easy, right? Luckily it’s only these that you’ll have to do with any sort of regularity.

6. Bonus: if things aren’t quite right

If steps 1 to 5 work for you, great. If not, you might want to try putting log4net into debug mode. This is really simple to do. If you look back at the configuration example above, you’ll see that the “log4net” element has a “debug” attribute, currently setting this to false. Setting this to true will result in log4net spitting out some (relatively verbose) debug statements to the console.

If you’re not finding anything in your logs, give this a go as a first pass. (If you don’t get any debugging output on-screen, double-check step 3 – log4net won’t even start debugging until we call it into being!) You may need to google some of the output, as it’s not necessarily actionable by itself.

Summary

Log4net is hugely powerful and flexible. This guide would have been a lot shorter if there was only one way to do things, but the flexibility is useful as long as you remember that some combinations won’t work (e.g. loading a config from app.config from inside AssemblyInfo.cs). In broad terms, the steps are pretty simple: grab the log4net package from NuGet, write some configuration, load the configuration, create a logger, and then log to it.

As I said at the beginning, I wanted to write this as an aide-mémoire, because I don’t do the early steps frequently enough for them to stick in my head. Ironically, I feel like the act of writing it down might have helped cement it for me at last, so perhaps I won’t need to refer back to it! Anyway, I hope it helps someone. If you’ve got any log4net tips or tricks, please let me know in the comments.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.