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.
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With