Title: Logging entry and exit of methods along with parameters automagically?
Tags: .net;logging;log4net
Question: Is there a way for me to add logging so that entering and exiting methods gets logged along with parameters automatically somehow for tracing purposes? How would I do so?

I am using Log4Net.



Here is another answer: Have a look at:

How do I intercept a method call in C#?
PostSharp - il weaving - thoughts

Also search SO for 'AOP' or 'Aspect Oriented Programming' and PostSharp...you get some interesting results.


Here is another answer: I'm not sure what your actual needs are, but here's a low-rent option.  It's not exactly "automatic", but you could use StackTrace to peel off the information you're looking for in a manner that wouldn't demand passing arguments - similar to ckramer's suggestion regarding interception:

```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Diagnostics;

namespace TracingSample
{
    class Program
    {
        static void Main(string[] args)
        {
            DoSomething();
        }

        static void DoSomething()
        {
            LogEnter();

            Console.WriteLine("Executing DoSomething");

            LogExit();
        }

        static void LogEnter()
        {
            StackTrace trace = new StackTrace();
            if (trace.FrameCount &gt; 1)
            {
                string ns = trace.GetFrame(1).GetMethod().DeclaringType.Namespace;
                string typeName = trace.GetFrame(1).GetMethod().DeclaringType.Name;
                Console.WriteLine("Entering {0}.{1}.{2}", ns, typeName, trace.GetFrame(1).GetMethod().Name);
            }
        }

        static void LogExit()
        {
            StackTrace trace = new StackTrace();
            if (trace.FrameCount &gt; 1)
            {
                string ns = trace.GetFrame(1).GetMethod().DeclaringType.Namespace;
                string typeName = trace.GetFrame(1).GetMethod().DeclaringType.Name;
                Console.WriteLine("Exiting {0}.{1}.{2}", ns, typeName, trace.GetFrame(1).GetMethod().Name);
            }
        }
    }
}
```

You could combine something like the above example with inheritance, using a non-virtual public member in the base type to signify the action method, then calling a virtual member to actually do the work:

```public abstract class BaseType
{
    public void SomeFunction()
    {

        LogEnter();
        DoSomeFunction();
        LogExit();
    }

    public abstract void DoSomeFunction();
}

public class SubType : BaseType
{
    public override void DoSomeFunction()
    {
        // Implementation of SomeFunction logic here...
    }
}
```

Again - there's not much "automatic" about this, but it would work on a limited basis if you didn't require instrumentation on every single method invocation.

Hope this helps.

Comment for this answer: This code goes well with this code to capture the parameter values
http://stackoverflow.com/a/6928253/1267778 . So I have something like logService.LogEnter(arg1, arg2, arg3). Great stuff

Here is another answer: The best way to achieve this sort of thing is by using interception,  There are a couple of ways to do this, though they all tend to be somewhat invasive.  One would be to derive all your objects from ContextBoundObject.  Here is an example of using this sort of approach.  The other approach would be to use one of the existing AOP libraries to achieve this.  Something like DynamicProxy from the Castle Project is at the core of many of these.  Here are a few links:
  Spring.Net
  PostSharp
  Cecil

There are probably several others, and I know Castle Windsor, and Ninject both provide AOP capabilities on top of the IoC functionality.

Once AOP is in place you would simply write an interceptor class that would write the information about the method calls out to log4net.

I actually wouldn't be surprised if one of the AOP frameworks would give you that sort of functionality out of the box.


Here is another answer: You can use open source framework CInject on CodePlex that has a LogInjector to mark entry and exit of a method call.

Or you can follow the steps mentioned on this article on Intercepting Method Calls using IL and create your own interceptor using Reflection.Emit classes in C#.


Here is another answer: You could use a post-compiler like Postsharp. The sample from the website talks about setting up a tracer for entering/exiting a method, which is very similar to what you want.


Here is another answer: Functions

To expand on Jared's answer, avoiding code repetition and including options for arguments:

```private static void LogEnterExit(bool isEnter = true, params object[] args)
{
    StackTrace trace = new StackTrace(true);  // need `true` for getting file and line info
    if (trace.FrameCount &gt; 2)
    {
        string ns = trace.GetFrame(2).GetMethod().DeclaringType.Namespace;
        string typeName = trace.GetFrame(2).GetMethod().DeclaringType.Name;
        string args_string = args.Length == 0 ? "" : "\narguments: [" + args.Aggregate((current, next) =&gt; string.Format("{0},{1};", current, next))+"]";
        Console.WriteLine("{0} {1}.{2}.{3}{4}", isEnter ? "Entering" : "Exiting", ns, typeName, trace.GetFrame(2).GetMethod().Name, args_string );
    }
}

static void LogEnter(params object[] args)
{
    LogEnterExit(true, args);
}

static void LogExit(params object[] args)
{
    LogEnterExit(false, args);
}
```

Usage

```static void DoSomething(string arg1)
{
    LogEnter(arg1);
    Console.WriteLine("Executing DoSomething");
    LogExit();
}
```

Output

In the console, this would be the output if ```DoSomething``` were run with "blah" as ```arg1```

```Entering Program.DoSomething
arguments: [blah]
Executing DoSomething
Exiting Program.DoSomething
```


Here is another answer: This does not apply to all C# applications but I am doing the following in an Asp.Net Core application to add logging to controller method calls by implementing the following interfaces:

IActionFilter, IAsyncActionFilter.

```public void OnActionExecuting(ActionExecutingContext context)    

public void OnActionExecuted(ActionExecutedContext context)    

public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)    
```


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 7, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 2.5', 'CreationDate': '2008:00:10/05/08', 'FavoriteCount': 3.0, 'PostTypeId': 1, 'Tags': '<.net><logging><log4net>', 'Title': 'Logging entry and exit of methods along with parameters automagically?', 'ViewCount': 13767, 'id': 171285, 'user_AboutMe': '', 'user_AccountId': 560516.0, 'user_DisplayName': 'Xerx', 'user_Reputation': 3715.0, 'user_Views': 137.0, 'user_id': 15771.0}}