Is it possible to profile individual methods via attributes in .NET?
I am currently trying to locate some of the bottle necks in a large legacy application that makes heavy use of static methods. Integrating a framework is simply not an option at the moment. Since most of the calls use static methods, interfaces and dependency injection are not available. Hacking the code to log diagnostics is not a viable solution either.
I know that there are some profiling tools on the market, but they are currently outside of the budget. Ideally, I would be able to create my own custom attribute that would log some basic information on method entry and method exit. I’ve never really worked with custom attributes so any insight into if this is even possible would be appreciated.
If possible, I’d like to be enable the profiling via a config file. This would support profiling via unit and integration tests.
You can’t use attributes for what you are doing. However, you do have some choices:
First, many of the profiler tools out there (like RedGate ANTS) are relatively inexpensive ($200-$300), easy to use, and most offer free evaluation periods of a couple of weeks – so you can see if they will give you the lift you need now, before you decide whether to buy them. Also, the .NET CLR profiler is free to download.
If that’s not possible, PostSharp is probably the easiest way to weave such logic into your code.
Lastly, if you can’t use PostSharp for whatever reason and you are willing to go and add attributes to your code, you may as well add a simple instrumentation block to each method in the form of a using block:
A typical MetricTracker implementation looks something like this: