Logging with Spring in .NET
Introduction
To avoid introducing a dependency on a particular logging framework Spring uses it's own logging abstraction: the "Common.Logging" library. This library is based on work done by the developers of IBatis.NET and it's usage is inspired by log4net. It provides an easy mechanism to plug in any logging framework using FactoryAdapters.
Configuring Logging
Declarative Configuration
Logging configuration can be done declaratively in your app.config:
<configuration>
<configSections>
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
</configSections>
<common>
<logging>
<factoryAdapter type="Common.Logging.Simple.TraceLoggerFactoryAdapter, Common.Logging">
<arg key="showDateTime" value="true" />
</factoryAdapter>
</logging>
</common>
</configuration>
The concrete set of <arg> elements you may specify depend on the FactoryAdapter being used.
Configuring Logging in your code
You may manually configure logging by setting a LoggerFactoryAdapter in your code:
// create properties
NameValueCollection properties = new NameValueCollection();
properties["showDateTime"] = "true";
// set Adapter
Common.Logging.LogManager.Adapter =
new Common.Logging.Simple.TraceLoggerFactoryAdapter(properties);
The concrete set of properties you may specify depend on the FactoryAdapter being used.
Using Common.Logging API in your own code
Usage of the Logging API is fairly simple. You need to obtain a logger from the LogManager and call the appropriate logging method:
using Common.Logging;
...
ILog log = LogManager.GetLogger(this.GetType());
log.Debug("hello world");
It is also possible to obtain a logger by name:
ILog log = LogManager.GetLogger("mylogger");
The methods available for logging are:
- Debug()
- Info()
- Warn()
- Error()
- Fatal()
All methods are overloaded to support logging exceptions as well.
Since ILog interface mimics the look&feel of log4net, migration is just a matter of changing the "using" statement.
Posted in: programming asp.net | Tags: .net c# asp.net configuration logging spring configuring logging configsections sectiongroup configurationsectionhandler factoryadapter