Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My logging framework is tied to my application forever!

Ok, so I'm looking at NLog. Based on the usage, my application would be tied to the logging framework. How do I overcome this?

Also, when using NLog, I have to write too much monkey-code for every class I'm using this framework on. Is it a good practice to make one static class and access it from anywhere in my application?

example:

//the monkey code
private static Logger logger = LogManager.GetCurrentClassLogger();

//the coupling.
logger.Log(/*...*/);
like image 986
Shawn Mclean Avatar asked Feb 13 '11 05:02

Shawn Mclean


1 Answers

  1. Create your own logging interface:

    public interface IMyOwnLogger {
        void Log(string message);
    }
    
  2. Create implementation:

    public class NLogLogger : IMyOwnLogger {
        void Log(string message) {
            StackFrame frame = new StackFrame(1, false);
            Logger logger = LogManager.GetLogger(frame.GetMethod().DeclaringType.FullName);
            logger.Log(/*...*/);
        }
    }
    
  3. Bind IMyOwnLogger to NLogLogger in your IOC container.

  4. Inject where needed (or use IOC.Get<IMyOwnLogger>()).

EDIT:

Idsa made a comment about loosing calling class. Remember you can always use stack trace:

var method = (new StackTrace()).GetFrame(1).GetMethod()

and extract calling class from there.

EDIT:

This is how GetCurrentClassLogger in NLog looks like, so using StackTrace in our class doesn't create additional overhead:

[MethodImpl(MethodImplOptions.NoInlining)]
public static Logger GetCurrentClassLogger()
{
    #if SILVERLIGHT
    StackFrame frame = new StackTrace().GetFrame(1);
    #else
    StackFrame frame = new StackFrame(1, false);
    #endif

    return globalFactory.GetLogger(frame.GetMethod().DeclaringType.FullName);
}
like image 118
LukLed Avatar answered Nov 16 '22 03:11

LukLed