Open sandboxFocusImprove this doc

Logging example, step 8: Avoiding infinite recursion

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:

Source Code



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}
Transformed Code
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
7#pragma warning disable CS8618, CS0649
8
9public class LogAttribute : OverrideMethodAspect
10{
11    [IntroduceDependency]
12    private readonly ILogger _logger;
13
14    public override dynamic? OverrideMethod()
15    {
16        // Determine if tracing is enabled.
17        var isTracingEnabled = this._logger.IsEnabled( LogLevel.Trace );
18
19        // Write entry message.
20        if ( isTracingEnabled )
21        {
22            var entryMessage = BuildInterpolatedString( false );
23            entryMessage.AddText( " started." );
24
25            using ( var guard = LoggingRecursionGuard.Begin() )
26            {
27                if ( guard.CanLog )
28                {
29                    this._logger.LogTrace( (string) entryMessage.ToValue() );
30                }
31            }
32        }
33
34        try
35        {
36            // Invoke the method and store the result in a variable.
37            var result = meta.Proceed();
38
39            if ( isTracingEnabled )
40            {
41                // Display the success message. The message is different when the method is void.
42                var successMessage = BuildInterpolatedString( true );
43
44                if ( meta.Target.Method.ReturnType.Equals( typeof(void) ) )
45                {
46                    // When the method is void, display a constant text.
47                    successMessage.AddText( " succeeded." );
48                }
49                else
50                {
51                    // When the method has a return value, add it to the message.
52                    successMessage.AddText( " returned " );
53
54                    if ( SensitiveParameterFilter.IsSensitive(
55                            meta.Target.Method
56                                .ReturnParameter ) )
57                    {
58                        successMessage.AddText( "<redacted>" );
59                    }
60                    else
61                    {
62                        successMessage.AddExpression( result );
63                    }
64
65                    successMessage.AddText( "." );
66                }
67
68                using ( var guard = LoggingRecursionGuard.Begin() )
69                {
70                    if ( guard.CanLog )
71                    {
72                        this._logger.LogTrace( (string) successMessage.ToValue() );
73                    }
74                }
75            }
76
77            return result;
78        }
79        catch ( Exception e ) when ( this._logger.IsEnabled( LogLevel.Warning ) )
80        {
81            // Display the failure message.
82            var failureMessage = BuildInterpolatedString( false );
83            failureMessage.AddText( " failed: " );
84            failureMessage.AddExpression( e.Message );
85
86            using ( var guard = LoggingRecursionGuard.Begin() )
87            {
88                if ( guard.CanLog )
89                {
90                    this._logger.LogWarning( (string) failureMessage.ToValue() );
91                }
92            }
93
94            throw;
95        }
96    }
97
98    // Builds an InterpolatedStringBuilder with the beginning of the message.
99    private static InterpolatedStringBuilder BuildInterpolatedString( bool includeOutParameters )
100    {
101        var stringBuilder = new InterpolatedStringBuilder();
102
103        // Include the type and method name.
104        stringBuilder.AddText( meta.Target.Type.ToDisplayString( CodeDisplayFormat.MinimallyQualified ) );
105        stringBuilder.AddText( "." );
106        stringBuilder.AddText( meta.Target.Method.Name );
107        stringBuilder.AddText( "(" );
108        var i = 0;
109
110        // Include a placeholder for each parameter.
111        foreach ( var p in meta.Target.Parameters )
112        {
113            var comma = i > 0 ? ", " : "";
114
115            if ( SensitiveParameterFilter.IsSensitive( p ) )
116            {
117                // Do not log sensitive parameters.
118                stringBuilder.AddText( $"{comma}{p.Name} = <redacted> " );
119            }
120            else if ( p.RefKind == RefKind.Out && !includeOutParameters )
121            {
122                // When the parameter is 'out', we cannot read the value.
123                stringBuilder.AddText( $"{comma}{p.Name} = <out> " );
124            }
125            else
126            {
127                // Otherwise, add the parameter value.
128                stringBuilder.AddText( $"{comma}{p.Name} = {{" );
129                stringBuilder.AddExpression( p );
130                stringBuilder.AddText( "}" );
131            }
132
133            i++;
134        }
135
136        stringBuilder.AddText( ")" );
137
138        return stringBuilder;
139    }
140}