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'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 > 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 > 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.