I use NLog for logging. I used to keep Logger property in every class I needed to log from and then have Winsdor container inject it with appropriate logger.
All of that changed when I switched to AutoFac and I wanted to simplify working with logger, especially since not all classes I want to log from are managed by the DI container.
The best solution I came up with is to use extension methods in .NET 3.5. Here's the code:
using System;
using NLog;
namespace Logging
{
public interface INeedToLog
{
}
public static class LogExtensions
{
public static Logger Log( this INeedToLog needToLogObj )
{
var type = needToLogObj.GetType();
return Logging.GetLogger( type );
}
}
public static class Logging
{
public static Logger GetLogger( Type typeToLogFrom )
{
return LogManager.GetLogger( typeToLogFrom.Name );
}
public static Logger GetLogger( object objectToLogFrom )
{
var typeToLogFrom = objectToLogFrom.GetType();
return LogManager.GetLogger( typeToLogFrom.Name );
}
}
}
I simply inherit from INeedToLog from any class in which I need to log. Then extension method Log becomes available and I can do something like this.
this.Log().Info( "Info text" );
This method for logging might be intrusive into interface hierarchy, but it's very simple to set up, even if you don't use DI. I like that!
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5