Sunday, August 3, 2014

Tracing with Unity

One of the most consistent issues that comes up with software is the need to improve performance.  Even if your application is really fast 99% of the time, someone will want you to improve it at some point.  That's just a fact of life.  The problem is that it's really hard to improve the overall performance of your application if you don't know where the performance is lacking.

I once had a boss who, upon learning that the performance of the new application was not to his standards, demanded that we fix it immediately.  When we pressed him for what was slow he answered "all of it" and "just the whole thing".  We said "let us put some logging in place so we can identify which parts are too slow and then we'll fix it", which was met with "no, just fix it now".

Ever since that incident, I've made it a point to build in a tracing feature that can be switched on or off with a small change to the configuration file.  Recently (as in, two days ago) I found that the old way of tracing wasn't working for me anymore and I had to figure out how to do it all over again.  Here is the fruit of my labor.

First, create the TraceCallHandler class:


Here's some more detail on that one:



The Invoke method is the one that actually interrupts the call.  You can see that all we're doing here is building the arguments list, getting the name of the method being called (including the type in which it's declared in case you have the same method name in multiple places), and starting a stopwatch around the actual method call.  We let the method do its thing, then log the whole shebang on a new thread.



I struggled with this one for a while, but ultimately settled on this.  Basically, I'm trying to see what parameters were used to call the method being executed.  This is helpful when the parameters are primitive types, but if a complex object is passed, it doesn't tell me a whole lot.



Basically at this point we're just passing the values we've collected into a stored procedure so we can review the data when we're ready.  And on that note, here's the stored procedure:



Aaaaaaand the table that stored procedure writes to:



To use the trace attribute all you have to do is add it as a decorator to the interface that has the methods you want to trace.  In this case we're going to trace all methods on the IAboutManager class:



But that'll only work if we configure tracing back in our Unity container.  Like this:



And then we have to configure the actual trace on the IAboutManager interface, like this:



And that's it.  That little bit of code (OK, it's a lot of code, but it did all fit in a single post) will enable tracing with two values from the web.config set to true.  Oh, I forgot that part.  Here you go:


No comments:

Post a Comment