Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging throughout class library without references passes

I have a class library in C# and it does lots of different functions for me. I want to be able to log throughout the class, however, I really don't want to have to pass instances of the logging library throughout.

e.g.

public void MyMethod(LoggingClass logger)
{
  logger.log("something");
}

public void MyMehtod2(LoggingClass logger)
{
  logger.log("something else");
}

I've got classes everywhere throughout this library and am struggling with a good way to do this. I've been looking at dependency injection with Ninject, but can't seem to get my head around how that should work.

So to summarize, I want to be able to have a logging class, and be able to instantiate it once, then use it everywhere to log.

like image 504
Steve Sloka Avatar asked Nov 08 '11 14:11

Steve Sloka


2 Answers

I don't see a need for a singleton. Simply use a static class in your library:

internal static class Logger {

static Logger() {

    // configure logger

}

internal static void Log(string Message, params object[] args) {

    var message = string.Format(Message, args);
    //  write message

}
like image 153
IAbstract Avatar answered Oct 11 '22 02:10

IAbstract


My preference would be extension methods that implement some static class as mentioned by @IAbstract. If your classes all implement your own ILog interface you could do it something like this:

public static void Log(this ILog source, string message)
{
    source.Log(message, null);
}

public static void Log(this ILog source, string message, param object[] args)
{
    // Assuming a static class as mentioned by @IAbstract
    Logger.Log(message, args);
}

Then in your classes or from wherever depending on the protection levels you'd be able to use this.Log(message) or externally myClass.Log(message). This wouldn't need to be public, but that would be dependent on the needs of the library.

like image 42
Joel Etherton Avatar answered Oct 11 '22 02:10

Joel Etherton