C# log all method calls of a class

2.2k Views Asked by At

I am trying to create a simple logger that logs all method calls for another class. That would include calls from a method in the same class, such as recursive calls.

(While there are answers to the "log incoming method calls to an observed class", I have not been able to find an answer to "log method calls from an observed class to itself". Please don't close as duplicate if the other answer does not address this issue)

The simplest solution would be to use a decorator as follows:

class Program
{
    static void Main(string[] args)
    {
        new LoggerDecorator(new Observed()).Do();
    }
}

public class Observed
{
    public void Do()
    {
        Console.WriteLine("Do");
    }
}

public class LoggerDecorator : Observed
{
    private Observed _subject;
    public LoggerDecorator(Observed subject)
    {
        _subject = subject;
    }
    public void Do()
    {
        Console.WriteLine("Log: Start Do");
        _subject.Do();
        Console.WriteLine("Log: End Do");
    }
}

This successfully logs calls from Main to the observed class' Do method:

Log: Start Do
Do
Log: End Do

Now, suppose we add a method Observed.DoTwice()

public void DoTwice()
{
    Do();
    Do();
}

and the corresponding logger:

public void DoTwice()
{
    Console.WriteLine("Log: Start DoTwice");
    _subject.DoTwice();
    Console.WriteLine("Log: End DoTwice");
}

Now we log any calls from Main to DoTwice but not the two calls from DoTwice to Do:

Log: Start DoTwice
Do
Do
Log: End DoTwice

What I want, is this:

Log: Start DoTwice
Log: Start Do
Do
Log: End Do
Log: Start Do
Do
Log: End Do
Log: End DoTwice

Of course, it cannot work like this because DoTwice calls its own Do method and not the overriding method in the decorator (it correctly doesn't even know about the decorator's existence). Since the decorator doesn't work, I tried to do the same thing with Unity interception, but it gave the same result.

Does anyone have an idea how to achieve this?

0

There are 0 best solutions below