1

For every WCF method, I need to have a log message right after the method is called, and another log message after the method ends. For example, the code may look like this:

public string Method1() 
{ 
  try {
    Log("Method1 start"); 
    /*implementation is here*/ 
  } 
  finally 
  { 
   Log("Method1 end");
  } 
}

The two logs need to contain the WCF method name. Now I need to add this to all WCF methods. Is it possible that I can create a generic method to do this, so that I do not need to repeat writing this on every WCF call?

2 Answers2

1

What you are looking for is Interceptors. WCF enables you to add interceptors in different stages of the request processing.

Implement an interceptor that will look like your example. For information about the interceptors


I'd recomment that your interceptor function will look something like this: To get the method name look at this SO question

{
    try
    {
        Log(string.Format("Entering method: {0}",/*function name*/));
        //proceed with execution
        Log(string.Format("Exiting method: {0}",/*function name*/));
    }
    catch (Exception exception)
    {
        Log(string.Format("Exiting method {0} with failure: {1}:,/*function name*/,exception.ToString());
}

  • What I also normally do is in the Entering message print values on input parameters if there are any, and also on Exiting in the case of a return value print it too. Makes log reading so much more usful.
Community
  • 1
  • 1
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
1

What you are looking for is called Aspect Oriented Programming.

AOP comes in different flavors and handles cross-cutting concerns like logging.

  • WCF Interception (see @Gilad answer)
  • IoC Interception (is a bit tricky to get to work with WCF, see more here)
  • PostSharp

PostSharp is a very nice tool that implements AOP on build time, whereas WCF and IoC interception is done runtime. But the general idea is the same. See more Here.

Michael
  • 3,350
  • 2
  • 21
  • 35