I have a c# web service. When I get a new request I create a logging instance. I have many other instances of other classes to process the request and I want them to log as well. What is the best way to share logging instance without passing it in constructors or properties ?
Often some sort of static class / property is used to share an object without needing to pass references everywhere, for example:
public class Logger
{
static Logger()
{
this.Instance - new Logger();
}
public static Logger Instance
{
get;
private set;
}
// Other non-static members
}
Usage:
Logger.Instance.Log();
Often this (or at least variations on this) are referred to as the singleton pattern.
There are many variations on the above, for example the following slight variation is more common than the above in logging frameworks:
public class Logger
{
static Logger()
{
this.Instance = new Logger();
}
public static Logger Instance
{
get;
private set;
}
public static void Log()
{
Logger.Instance.Log();
}
}
Usage:
Logger.Log();
Singleton Pattern is an anti-pattern; I can not think of many instances where it should be used or recommended, including in this instance, for logging.
How we handle logging: A logging instance is injected into all classes that need it via constructor injection. For example:
public class MyClass
{
private readonly ILogger _logger;
public MyClass(ILogger logger)
{
_logger = logger;
}
public void DoStuff()
{
_logger.Trace("DoStuff called");
}
}
The logging instance injected can either be a new instance each time, or if you are bent on having a single instance logger it can be created once and passed through as needed.
However: I strongly recommend the first option, using DI to construct your classes using the Composition Root pattern. I also recommend using a logging framework, such as NLog or log4net. These are configurable and easy to use with emails, event viewer, files, etc. and work in multi threaded environments.
We have our own definition of ILogger which has Trace, Warn, Info, Exception, etc., and then implemented this interface using NLog. This means that we can easily change how we log by creating a new implementation of ILogger and then making a simple DI config update. This is one logging solution that has worked really well for us so far.
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