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?
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 > 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) => 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);
}
static void DoSomething(string arg1)
{
LogEnter(arg1);
Console.WriteLine("Executing DoSomething");
LogExit();
}
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