0

I am logging the function calls into a log file. I am using log4Net for the same

 public Registration Check(Registration registration)
        {

                loggingProvider.Entry();
                //Some code Here
                loggingProvider.Exit();
                return something;
        } 

Now if i have to make an entry of a function call i have to manually add loggingProvider.Entry() inside every function.

Is there a way where I can log all function calls happening inside a given namespace with minimal LOC? Like writing a function in just one place which will log all functions calls happening?

I tried to get the name of the function being called from the constructor/destructor using the stacktrace and log it but its not possible.

Please provide me any alternate way to get the function names that are being called without manually adding log function inside each and every function.

Community
  • 1
  • 1
Vignesh Subramanian
  • 7,161
  • 14
  • 87
  • 150

1 Answers1

3

Postsharp would be able to help with this.

http://www.postsharp.net/

Look at injecting behaviour before and after method invocation on http://doc.postsharp.net/method-decorator

As an example, this was taken from their site

[Serializable]
public sealed class TraceAttribute : OnMethodBoundaryAspect
{
    // This field is initialized and serialized at build time, then deserialized at runtime.
    private readonly string category;

    // These fields are initialized at runtime. They do not need to be serialized.
    [NonSerialized] private string enteringMessage;
    [NonSerialized] private string exitingMessage;

    // Default constructor, invoked at build time.
    public TraceAttribute()
    {
    }

    // Constructor specifying the tracing category, invoked at build time.
    public TraceAttribute(string category)
    {
        this.category = category;
    }


    // Invoked only once at runtime from the static constructor of type declaring the target method.
    public override void RuntimeInitialize(MethodBase method)
    {
        string methodName = method.DeclaringType.FullName + method.Name;
        this.enteringMessage = "Entering " + methodName;
        this.exitingMessage = "Exiting " + methodName;
    }

    // Invoked at runtime before that target method is invoked.
    public override void OnEntry(MethodExecutionArgs args)
    {
        Trace.WriteLine(this.enteringMessage, this.category);
    }

    // Invoked at runtime after the target method is invoked (in a finally block).
    public override void OnExit(MethodExecutionArgs args)
    {
        Trace.WriteLine(this.exitingMessage, this.category);
    }
}

Methods that need to be traced(logged in your case) can be decorated by using [Trace], it should also be possible to create a class level aspect, where you can decorate the class that should have the logging associated, although I haven't done that myself.

3dd
  • 2,520
  • 13
  • 20