Castle Windsor comes with what it calls a “Logging Facility“. What the latter allows you to do is very quickly enable logging using a variety of ways but what is most interesting is the fact that the “Logging Facility” provides the necessary plumbing for swapping one type of logger for another. So for instance, you can change from log4net to NLog very easily by simply changing one line of code.
In fact, that’s what I had to do i.e. swap out log4net for NLog because I had started logging using the former but then found out that the latter might possibly be better.
While there are examples of how to use the “Logging Facility” with log4net, I haven’t found any with dealt specifically with NLog integration and Castle Windsor in detail. While the resources provided earlier do help and can be used to figure out how to get NLog integration, the information needed aggregating which this post attempts to address.
Set up Castle Windsor NLog integration
This is very straighforward if you use Nuget. Simply add the package “Castle Windsor NLog” to your project.
The former is how you will configure NLog i.e. where to create the log file, etc while the latter will provide intellisense while editing the configuration file.
So here’s how you might want to configure logging:
The next step is to ensure that CastleWindsor will use NLog to perform logging:
container.AddFacility<LoggingFacility>(f => f.LogUsing(LoggerImplementation.NLog) .WithConfig("NLog.config"));
If let’s say you want to use log4net instead then instead simply use (assuming you’ve got the “log4.net.config” present):
container.AddFacility<LoggingFacility>(f => f.LogUsing(LoggerImplementation.Log4net) .WithConfig("log4net.config"));
Now according to best practice advice to set up logging:
Finally, log whatever you want e.g.:
I’ve put together the source code here.