views:

173

answers:

5

I have written a large C# app with many methods in many classes.

I'm trying to keep a log of what gets called and how often during my development. (I keep a record in a DB)

Every method is padded with the following calls:

void myMethod()
{
log(entering,args[]);

log(exiting,args[]);
}

Since I want to do this for all my methods, is there a better way to do this then having to replicate those lines of code in every method?

+1  A: 

Well, you could use some kind of Decorator on your classes to log things, but I think the better approach is to use some kind of profiling tool in your build and/or unit testing process. You can pretty easily get a lot of value out of some simple metric collection in CruiseControl, etc.

Peter Loron
+4  A: 

Take a look at http://www.postsharp.org/

Here's the first example on their front page:

public class TraceAttribute : OnMethodBoundaryAspect 
{ 
  public override void OnEntry( MethodExecutionEventArgs eventArgs) 
  { Trace.TraceInformation("Entering {0}.", eventArgs.Method);  } 

  public override void OnExit( MethodExecutionEventArgs eventArgs) 
  { Trace.TraceInformation("Leaving {0}.", eventArgs.Method);   } 
}

Seems to be exactly what you need!

Blorgbeard
Oh wow! that's awesome! Thanks.
Matt
+1  A: 

You need a profiler. There are two "main" ones for C#. JetBrains "dotTrace" and "YourKit" both are good but I prefer YourKit. It's a good investment. I think you will find that you wont use it a whole lot...but when you DO need one they are awesome.

ryber
+1  A: 

If what you're really after is prevention of performance problems, that's exactly the kind of situation where I've found this works best.

Just this morning somebody sent me a really big dataset to run in the large C# app our company is building. It was so slow I could barely resist killing it.

Since I was running under the VS IDE, I just paused it a few times and looked at what it was doing and why. It was doing something that no amount of logging or guessing would have found. The fix was trivial, and the speedup dramatic.

When performance problems are less bad than that, it may take several more samples to find them, but it always works and couldn't be simpler.

Mike Dunlavey
A: 

Try looking into AOP.

devlife