You are viewing a plain text version of this content. The canonical link for it is here.
Posted to log4net-user@logging.apache.org by Ron Grabowski <ro...@yahoo.com> on 2005/07/07 15:54:58 UTC
Implementing your own logger for log4net
Occasionly I'll recommend people "extend log4net and write your own
logger" if the default behaviour of log4net doesn't do what they need.
The usually routine is to post a link to this page:
http://cvs.apache.org/viewcvs.cgi/logging-log4net/extensions/net/1.0/
The examples on that page are well written and well documented. If you
need something even simpler, take a look at the code below. I've
implemented a VerySimpleLogger that contains only two log methods:
Trace and Alert. Log4net has support for a lot of other log levels
besides the familiar Debug, Info, Warn, etc. Here's a sample usage:
log4net.Config.XmlConfigurator.Configure();
static VerySimpleLogger log = LogManager.GetLogger("Class1");
log.Trace("Hello World");
log.Trace(1234, "Hello World");
log.Alert("Hello World");
The VerySimplerLogger class is "faster" than ILog becuase you're making
calls to a sealed concrete class rather than an interface. For
maintainability, I'd recommend using the standard ILog interface
whenever possible.
public sealed class LogManager
{
private static readonly WrapperMap s_wrapperMap = new WrapperMap(
new WrapperCreationHandler(WrapperCreationHandler));
private LogManager()
{
}
public static VerySimpleLogger GetLogger(string name)
{
return (VerySimpleLogger)s_wrapperMap.GetWrapper(
LoggerManager.GetLogger(Assembly.GetCallingAssembly(), name));
}
private static ILoggerWrapper WrapperCreationHandler(ILogger logger)
{
return new VerySimpleLogger(logger);
}
}
public sealed class VerySimpleLogger : LoggerWrapperImpl
{
private readonly static Type declaringType = typeof(VerySimpleLogger);
public VerySimpleLogger(ILogger logger) : base(logger)
{
}
public void Trace(string message)
{
Logger.Log(declaringType, Level.Trace, message, null);
}
public void Trace(int id, string message)
{
LoggingEvent loggingEvent = new LoggingEvent(
declaringType,
Logger.Repository,
Logger.Name,
Level.Trace,
message,
null);
loggingEvent.Properties["id"] = id;
Logger.Log(loggingEvent);
}
public void Alert(string message)
{
Logger.Log(declaringType, Level.Alert, message, null);
}
}