views:

68

answers:

6

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 ?

A: 

Well, you could make your logging class contain static methods which do the actual writing into memory/flushing to disk. You could also look into the Singleton Pattern

Ed Swangren
A: 

Use a static field (I assume C# supports theses). The syntax should be similar to this:

private static final Logger logger = new Logger(...);

and just use that whenever you need to log something in the class.

alpha123
I think you meant readonly instead of final?
Jakub Konecki
I'm a Java developer. It's `final` for us. ;-). Yeah, that's my final answer....
alpha123
A: 

You can use the Singleton Pattern to ensure that there is only a single instance of your logging object across the system.

Passing the logging object into the Constructor or as a property will actually make your code easier to test, depending on how you implement the Singleton pattern. Logging is one of those annoying cross-cutting concerns that always has trade-offs.

Ozten
A: 

Usually it's not a problem to create a new instance of your logger in each class. Log4Net logger constructor takes a type as a parameter to give you better logs.

Jakub Konecki
+2  A: 

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();
Kragen
This is an optimal solution; put Logger in its own library so you can reference it from every other project.
Steven A. Lowe
+2  A: 

Singleton Pattern.

That is, a class with a private constructor. You use a public static method to create only one instance of the class and return the object.

edit: also worth noting that you will need to put this class in its own project so that it can be referenced by all classes.

stevenroberts