Excellent answer from Jon Skeet.
However, if you don't use .NET 4.5
, you can try reflection
. How ever you should know that reflection must be used only when it is absolutely necessary. Do not over-use it for the sake of using it
.
Coming back,
You could do something like,
using System.Reflection; //include Reflection namespace
Console.WriteLine(MethodBase.GetCurrentMethod().Name) //Get the method-name of the current method
In your case, it would be like below,
private void Method1()
{
//Do something
Log("Something", System.Reflection.MethodBase.GetCurrentMethod().Name);
}
private void Method2()
{
//Do something
Log("Something", System.Reflection.MethodBase.GetCurrentMethod().Name);
}
private void Log(string message, string method)
{
//Write to a log file
Trace.TraceInformation(message + "happened at " + method);
}
EDIT:
As per the below comments from @Jon Skeet's, if you want .Net 4.5
kind of fancy and neat implementation, check out the Micrsoft.Bcl
NUGET Package.