Månad: mars 2010

Which method called me?

I wanted a general function to log all calls to a WCF service a built, I want the calling method names without use that as a parameter and then need to hardcode that in every method. This is the solution it show how to found out the calling method using the stack trace.
 

internal static void LogRequest(IRequest request)
{
   
var callingMethod = new System.Diagnostics.StackTrace(1, false).GetFrame(0).GetMethod();
   
if(request != null)
    {
       
var applicationId = request.Header != null ? request.Header.ApplicationId : "unkown";
       
Log.Info(string.Format("{0} called by {1} Application ", callingMethod.Name, applicationId));
    }
   
else
   
{
       
Log.Error(string.Format("{0} called by Application with a null request, thats not allowed", callingMethod.Name));
    }
}

Annonser