Steve Sloka
Steve Sloka

Reputation: 3454

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.

Upvotes: 6

Views: 1984

Answers (3)

IAbstract
IAbstract

Reputation: 19881

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

}

Upvotes: 5

Joel Etherton
Joel Etherton

Reputation: 37533

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.

Upvotes: 1

CodeCaster
CodeCaster

Reputation: 151594

You could use a singleton for your logger, and call it like Logger.GetInstance().Log(something) from wherever you like.

Upvotes: 0

Related Questions