One way to do this is to use a linker, such as "Fody," with an extension that does exactly what you are looking for. See this link for an example extension: https://github.com/Fody/MethodTimer
How Fody works, it injects code into its codebase at compile time, using attributes, as you suggested in your answer. The provided extension works the same as you described, using a stopwatch to record the execution time of your code.
Edit: usage example:
After installing the library, you can add the [Time] annotation to the methods that you want to measure:
[Time] public void TestMethod() {
Then you can create a custom interceptor (a static class that will be automatically loaded by the Fody extension) that you use to add a metric track to application information:
public static class MethodTimeLogger { public static void Log(MethodBase methodBase, long milliseconds) { var sample = new MetricTelemetry(); sample.Name = methodBase.Name; sample.Value = milliseconds;
source share