I am trying to "inject" custom tracing methods in my application.
I want to make it as elegant as possible, without modifying to much of the existing code, and have the possibility to enable / disable it easily.
One solution i could think of would be to create a custom Attribute
which i will attach it to the methods i want to trace.
Basic idea:
public class MethodSnifferAttribute : Attribute
{
private Stopwatch sw = null;
public void BeforeExecution()
{
sw = new Stopwatch();
sw.Start();
}
public void ExecutionEnd()
{
sw.Stop();
LoggerManager.Logger.Log("Execution time: " + sw.ElapsedMilliseconds);
}
}
public class MyClass
{
[MethodSniffer]
public void Function()
{
// do a long task
}
}
Are there any existing .NET
attributes that provides callbacks for when a method is called / ended?
Attribute's method are not called unless you call it manually. There are security attributes which are invoked by the CLR but that's beyond the subject of this question and it will not be useful anyway.
There are techniques to rewrite your code at different level. Source code weaving, IL weaving etc.
You need to look at some way to modify the IL and rewrite it for timing the execution. Don't worry, you don't have to write all of that. People have already done it. For example, you can use PostSharp.
Here's an article which provides an example
Note: I've modified the example from the article to use
StopWatch
instead ofDateTime
becauseDateTime
isn't accurate.