I would like to write a reusable function I can call within any method to log a snapshot of all the local variables. For example:
void somemethod()
It is possible by using external debugger for managed code. See "managed debugger sample" for how it is done: http://blogs.msdn.com/b/jmstall/archive/2004/09/30/236281.aspx (includes link to the sample and more information)
Consider to write minidumps using a custom PostSharp aspect (with IL transformation).
A shared debuging engine library, written in C#. is available on NuGet as Microsoft.Samples.Debugging.MdbgEngine.
The code of PostSharp aspect is available on GitHub as part of the PADRE ( Pluggable Automatic Debugging and Reporting Engine)repository
See this related question:
Is there a simple way to obtain all the local variables in the current stack frame in C# (or CIL)
The short answer is: you can't get the values of the local variables because they're allocated directly on the stack at runtime, and thus are not available via reflection. The only way to do this is via the debugger API...and it's far from trivial. Further, this would only work if your custom debugger is actually attached to the process.
A better, more feasible option might be via assembly weaving. You said you don't want to have the method have to know the specific names of local variables to access when logging their values. I would suggest creating two methods:
static void LogVariables();
and
static void LogVariables(params string[] names, params object[] values);
Add a post build task that calls an assembly weaving routine that swaps out the first LogVariables call with the second, but explicitly providing the variable names/values to the method. You can write this routine to modify the assembly using Mono Cecil (there are other tools too that can do this).
http://www.mono-project.com/Cecil