Infinite recursion can occur when the logging logic of one method calls the logging logic of another method. Infinite recursion can cause stack overflow exceptions, resulting in crashes or unintended side effects. It consumes system resources, thus negatively affecting performance and potentially rendering the application, and any other application on the same device, unresponsive. In addition, excessive log entries generated by recursion make it difficult to locate the real cause of the problem, complicate log analysis, and increase storage requirements.
Therefore, infinite recursions in logging must be avoided at all costs.
To make this possible, a first step is to avoid logging the ToString
method. However, sometimes a
non-logged ToString
method can access logged properties or methods, and indirectly cause an infinite recursion. The
most reliable approach is to add the following code in the logging pattern:
using ( var guard = LoggingRecursionGuard.Begin() )
{
if ( guard.CanLog )
{
this._logger.LogTrace( message );
}
}
We can update the previous example with this new approach:
1public class LoginService
2{
3 // The 'password' parameter will not be logged because of its name.
4 public bool VerifyPassword( string account, string password ) => account == password;
5
6 [return: NotLogged]
7 public string GetSaltedHash( string account, string password, [NotLogged] string salt )
8 => account + password + salt;
9}
1using System;
2using Microsoft.Extensions.Logging;
3
4public class LoginService
5{
6 // The 'password' parameter will not be logged because of its name.
7 public bool VerifyPassword( string account, string password ) { var isTracingEnabled = _logger.IsEnabled(LogLevel.Trace);
8 if (isTracingEnabled)
9 {
10 using (var guard = LoggingRecursionGuard.Begin())
11 {
12 if (guard.CanLog)
13 {
14 _logger.LogTrace($"LoginService.VerifyPassword(account = {{{account}}}, password = <redacted> ) started.");
15 }
16 }
17 }
18
19 try
20 {
21 bool result;
22 result = account == password;
23 if (isTracingEnabled)
24 {
25 using (var guard_1 = LoggingRecursionGuard.Begin())
26 {
27 if (guard_1.CanLog)
28 {
29 _logger.LogTrace($"LoginService.VerifyPassword(account = {{{account}}}, password = <redacted> ) returned {result}.");
30 }
31 }
32 }
33
34 return (bool)result;
35 }
36 catch (Exception e) when (_logger.IsEnabled(LogLevel.Warning))
37 {
38 using (var guard_2 = LoggingRecursionGuard.Begin())
39 {
40 if (guard_2.CanLog)
41 {
42 _logger.LogWarning($"LoginService.VerifyPassword(account = {{{account}}}, password = <redacted> ) failed: {e.Message}");
43 }
44 }
45
46 throw;
47 }
48 }
49
50 [return: NotLogged]
51 public string GetSaltedHash( string account, string password, [NotLogged] string salt )
52 { var isTracingEnabled = _logger.IsEnabled(LogLevel.Trace);
53 if (isTracingEnabled)
54 {
55 using (var guard = LoggingRecursionGuard.Begin())
56 {
57 if (guard.CanLog)
58 {
59 _logger.LogTrace($"LoginService.GetSaltedHash(account = {{{account}}}, password = <redacted> , salt = <redacted> ) started.");
60 }
61 }
62 }
63
64 try
65 {
66 string result;
67 result = account + password + salt;
68 if (isTracingEnabled)
69 {
70 using (var guard_1 = LoggingRecursionGuard.Begin())
71 {
72 if (guard_1.CanLog)
73 {
74 _logger.LogTrace($"LoginService.GetSaltedHash(account = {{{account}}}, password = <redacted> , salt = <redacted> ) returned <redacted>.");
75 }
76 }
77 }
78
79 return (string)result;
80 }
81 catch (Exception e) when (_logger.IsEnabled(LogLevel.Warning))
82 {
83 using (var guard_2 = LoggingRecursionGuard.Begin())
84 {
85 if (guard_2.CanLog)
86 {
87 _logger.LogWarning($"LoginService.GetSaltedHash(account = {{{account}}}, password = <redacted> , salt = <redacted> ) failed: {e.Message}");
88 }
89 }
90
91 throw;
92 }
93 }
94private ILogger _logger;
95
96 public LoginService(ILogger<LoginService> logger = null)
97 {
98 this._logger = logger ?? throw new System.ArgumentNullException(nameof(logger));
99 }
100}
Infrastructure code
LoggingRecursionGuard
uses a thread-static field to indicate whether logging is currently occurring:
1internal static class LoggingRecursionGuard
2{
3 [ThreadStatic]
4 public static bool IsLogging;
5
6 public static DisposeCookie Begin()
7 {
8 if ( IsLogging )
9 {
10 return new DisposeCookie( false );
11 }
12 else
13 {
14 IsLogging = true;
15
16 return new DisposeCookie( true );
17 }
18 }
19
20 internal class DisposeCookie : IDisposable
21 {
22 public DisposeCookie( bool canLog )
23 {
24 this.CanLog = canLog;
25 }
26
27 public bool CanLog { get; }
28
29 public void Dispose()
30 {
31 if ( this.CanLog )
32 {
33 IsLogging = false;
34 }
35 }
36 }
37}
Aspect code
The LogAttribute
code has been updated as follows:
1using Metalama.Extensions.DependencyInjection;
2using Metalama.Framework.Aspects;
3using Metalama.Framework.Code;
4using Metalama.Framework.Code.SyntaxBuilders;
5using Microsoft.Extensions.Logging;
6
7public class LogAttribute : OverrideMethodAspect
8{
9 [IntroduceDependency]
Warning CS0649: Field 'LogAttribute._logger' is never assigned to, and will always have its default value null
10 private readonly ILogger _logger;
11
12 public override dynamic? OverrideMethod()
13 {
14 // Determine if tracing is enabled.
15 var isTracingEnabled = this._logger.IsEnabled( LogLevel.Trace );
16
17 // Write entry message.
18 if ( isTracingEnabled )
19 {
20 var entryMessage = BuildInterpolatedString( false );
21 entryMessage.AddText( " started." );
22
23 using ( var guard = LoggingRecursionGuard.Begin() )
24 {
25 if ( guard.CanLog )
26 {
27 this._logger.LogTrace( (string) entryMessage.ToValue() );
28 }
29 }
30 }
31
32 try
33 {
34 // Invoke the method and store the result in a variable.
35 var result = meta.Proceed();
36
37 if ( isTracingEnabled )
38 {
39 // Display the success message. The message is different when the method is void.
40 var successMessage = BuildInterpolatedString( true );
41
42 if ( meta.Target.Method.ReturnType.Equals( SpecialType.Void ) )
43 {
44 // When the method is void, display a constant text.
45 successMessage.AddText( " succeeded." );
46 }
47 else
48 {
49 // When the method has a return value, add it to the message.
50 successMessage.AddText( " returned " );
51
52 if ( SensitiveParameterFilter.IsSensitive(
53 meta.Target.Method
54 .ReturnParameter ) )
55 {
56 successMessage.AddText( "<redacted>" );
57 }
58 else
59 {
60 successMessage.AddExpression( result );
61 }
62
63 successMessage.AddText( "." );
64 }
65
66 using ( var guard = LoggingRecursionGuard.Begin() )
67 {
68 if ( guard.CanLog )
69 {
70 this._logger.LogTrace( (string) successMessage.ToValue() );
71 }
72 }
73 }
74
75 return result;
76 }
77 catch ( Exception e ) when ( this._logger.IsEnabled( LogLevel.Warning ) )
78 {
79 // Display the failure message.
80 var failureMessage = BuildInterpolatedString( false );
81 failureMessage.AddText( " failed: " );
82 failureMessage.AddExpression( e.Message );
83
84 using ( var guard = LoggingRecursionGuard.Begin() )
85 {
86 if ( guard.CanLog )
87 {
88 this._logger.LogWarning( (string) failureMessage.ToValue() );
89 }
90 }
91
92 throw;
93 }
94 }
95
96 // Builds an InterpolatedStringBuilder with the beginning of the message.
97 private static InterpolatedStringBuilder BuildInterpolatedString( bool includeOutParameters )
98 {
99 var stringBuilder = new InterpolatedStringBuilder();
100
101 // Include the type and method name.
102 stringBuilder.AddText( meta.Target.Type.ToDisplayString( CodeDisplayFormat.MinimallyQualified ) );
103 stringBuilder.AddText( "." );
104 stringBuilder.AddText( meta.Target.Method.Name );
105 stringBuilder.AddText( "(" );
106 var i = 0;
107
108 // Include a placeholder for each parameter.
109 foreach ( var p in meta.Target.Parameters )
110 {
111 var comma = i > 0 ? ", " : "";
112
113 if ( SensitiveParameterFilter.IsSensitive( p ) )
114 {
115 // Do not log sensitive parameters.
116 stringBuilder.AddText( $"{comma}{p.Name} = <redacted> " );
117 }
118 else if ( p.RefKind == RefKind.Out && !includeOutParameters )
119 {
120 // When the parameter is 'out', we cannot read the value.
121 stringBuilder.AddText( $"{comma}{p.Name} = <out> " );
122 }
123 else
124 {
125 // Otherwise, add the parameter value.
126 stringBuilder.AddText( $"{comma}{p.Name} = {{" );
127 stringBuilder.AddExpression( p );
128 stringBuilder.AddText( "}" );
129 }
130
131 i++;
132 }
133
134 stringBuilder.AddText( ")" );
135
136 return stringBuilder;
137 }
138}