Configuring Log4Net with Unity
This is part one of a three part series on adding logging to a Web API project using AOP (Aspect Oriented Programming). The following code is a simple way to inject logging into your web api project using log4net and Microsoft Unity.
I used the following Nuget packages.
PM> Install-Package Unity
PM> Install-Package log4net
PM> Install-Package UnityLog4NetExtension
The first thing you need is to do is setup Log4net. Below you will find the code for a basic log4net setup method.
Add a log creation class that inherits UnityContainerExtension. This will allow Unity to create and config your log file, rather than calling the logger setup in the global.asax.
public class LogCreation : UnityContainerExtension
{
protected override void Initialize()
{
Logger.Setup();
}
}
Register Log4Net with your Unity Container. Typically found in the UnityConfig.cs.
var container = new UnityContainer()
.AddNewExtension<LogCreation>()
.AddNewExtension<Log4NetExtension>(); //UnityLog4netExtension
Below is an example of my basic Microsoft Unity configuration file.
In the next post I will document on how to add logging to your controllers with AOP.