In the previous example, a generic message was logged when a method started. This was not very useful when the aspect was applied to multiple methods. In this example, the aspect is improved to include the name and signature of the executed method.
The logging aspect generates the green code in the snippet below:
Source Code
1internal static class Calculator
2{
3 [Log]
4 public static double Add( double a, double b ) => a + b;
5}
Transformed Code
1using System;
2
3internal static class Calculator
4{
5 [Log]
6 public static double Add( double a, double b ) { Console.WriteLine("Calculator.Add(double, double) started.");
7 try
8 {
9 double result;
10 result = a + b;
11 Console.WriteLine("Calculator.Add(double, double) succeeded.");
12 return (double)result;
13 }
14 catch (Exception e)
15 {
16 Console.WriteLine($"Calculator.Add(double, double) failed: {e.Message}.");
17 throw;
18 }
19 }
20}
Implementation
The aspect at work is the following:
1using Metalama.Framework.Aspects;
2
3public class LogAttribute : OverrideMethodAspect
4{
5 public override dynamic? OverrideMethod()
6 {
7 Console.WriteLine( $"{meta.Target.Method} started." );
8
9 try
10 {
11 var result = meta.Proceed();
12
13 Console.WriteLine( $"{meta.Target.Method} succeeded." );
14
15 return result;
16 }
17 catch ( Exception e )
18 {
19 Console.WriteLine( $"{meta.Target.Method} failed: {e.Message}." );
20
21 throw;
22 }
23 }
24}
The meta.Target.Method
expression is used in an interpolated string to get the method name and signature. The meta
pseudo-keyword means that the expression on the right side is evaluated at compile-time.