Reputation: 123
private void Method1()
{
//Do something
Log("Something","Method1");
}
private void Method2()
{
//Do something
Log("Something","Method2");
}
private void Log(string message, string method)
{
//Write to a log file
Trace.TraceInformation(message + "happened at " + method);
}
I have several methods like Method1 and Method2 above, and i would like some way pass the method's name as a parameter, without manually editing the code.
Is that possible?
Upvotes: 11
Views: 6477
Reputation: 1503290
As of C# 5, this is really easy using caller info attributes:
private void Method1()
{
//Do something
Log("Something");
}
private void Method2()
{
//Do something
Log("Something");
}
private void Log(string message, [CallerMemberName] string method = null)
{
//Write to a log file
Trace.TraceInformation(message + "happened at " + method);
}
In terms of getting this working:
Microsoft.Bcl
NuGet packageUpvotes: 23
Reputation: 9396
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.
Upvotes: 6
Reputation: 59615
Aspect Oriented Programming (AOP) usually allows to achieve such tasks. You can have a look at the free version of PostSharp, especially the Logging aspect is helpful in your case.
Your code then looks like this:
[LogAspect("Something")]
void Method1(string name)
{
}
You can use PostSharp down to .NET framework 2.0.
Upvotes: 0