Using log4net with OpenRasta

OpenRasta comes with a built in TraceLogger, but if you use log4net in your code then it’s easier to have all your log output going to the same destination. Thanks to ORs excellent pluggable architecture, it’s easy to supply your own implementation of ILogger:

using System;
using log4net;
using OpenRasta;
using OpenRasta.Diagnostics;

namespace Your.Namespace.Here
{
	public class Log4NetLogger : ILogger
	{
		private readonly ILog _log;

		public Log4NetLogger(ILog log)
		{
			_log = log;
		}

		public IDisposable Operation(object source, string name)
		{
			_log.DebugFormat("Entering {0}: {1}", source.GetType().Name, name);
			return new OperationCookie(_log, source);
		}

		public void WriteDebug(string message, params object[] format)
		{
			_log.DebugFormat(message, format);
		}

		public void WriteWarning(string message, params object[] format)
		{
			_log.WarnFormat(message, format);
		}

		public void WriteError(string message, params object[] format)
		{
			_log.ErrorFormat(message, format);
		}

		public void WriteInfo(string message, params object[] format)
		{
			_log.InfoFormat(message, format);
		}

		public void WriteException(Exception e)
		{
			_log.Error("Exception", e);
		}

		private class OperationCookie : IDisposable
		{
			private readonly ILog _log;
			private readonly object _source;

			public OperationCookie(ILog log, object source)
			{
				_log = log;
				_source = source;
			}

			public void Dispose()
			{
				_log.DebugFormat("Exiting {0}".With(_source.GetType().Name));
			}
		}
	}

	public class Log4NetLogger<T> : Log4NetLogger, ILogger<T> where T : ILogSource
	{
		public Log4NetLogger() : base(LogManager.GetLogger(LogSource<T>.Category)) { }
	}
}

This then needs to be supplied to the dependency resolver, for ILogger & ILogger<T> along with an ILog.

2 thoughts on “Using log4net with OpenRasta

  1. Gregzilla February 24, 2011 / 11:44 am

    Thanks ghay, smashing work. Worth pointing out that as it’s an OpenRasta.Diagnostics.ILogger, you need to:

    .ConfigureFor<OpenRasta.Diagnostics.ILogger>

    rather than:

    .ConfigureFor<Log4Net.Core.ILogger> like I’ve just stupidly been doing….

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s