Simplest way to logging

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

Posted by: Slava
Posted on: 7/28/2008 at 11:43 AM
Categories: .NET
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Related posts

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

Friday, November 21, 2008 5:27 AM