Metalama//Commented Examples/Logging
Open sandboxFocus

Example: Logging

Logging is a key aspect of application development, enabling developers to understand the execution flow and identify bottlenecks. Tracing helps optimize performance, pinpoint issues, and improve user experience by providing detailed insights into system interactions. It plays a significant role in ensuring efficient and reliable software.


This series of examples shows how to build an aspect that automatically writes a log record when a method execution starts, completes, or fails.

The objective is to transform the code as illustrated in the following example. If the generated code does not fit entirely to your preferences, do not worry, you can learn how to personalize it.

Source Code

1internal class Calculator
3    [Log]
4    public double Add( double a, double b ) => a + b;

Transformed Code
1using System;
2using Microsoft.Extensions.Logging;
4internal class Calculator
6    [Log]
7    public double Add( double a, double b )
9        var isTracingEnabled = this._logger.IsEnabled(LogLevel.Trace);
10        if (isTracingEnabled)
11        {
12            LoggerExtensions.LogTrace(this._logger, $"Calculator.Add(a = {{{a}}}, b = {{{b}}}) started.");
13        }
15        try
16        {
17            double result;
18            result = a + b;
19            if (isTracingEnabled)
20            {
21                LoggerExtensions.LogTrace(this._logger, $"Calculator.Add(a = {{{a}}}, b = {{{b}}}) returned {result}.");
22            }
24            return (double)result;
25        }
26        catch (Exception e) when (this._logger.IsEnabled(LogLevel.Warning))
27        {
28            LoggerExtensions.LogWarning(this._logger, $"Calculator.Add(a = {{{a}}}, b = {{{b}}}) failed: {e.Message}");
29            throw;
30        }
31    }
33    private ILogger _logger;
35    public Calculator
36    (ILogger<Calculator> logger = default)
37    {
38        this._logger = logger ?? throw new System.ArgumentNullException(nameof(logger));
39    }

In this series

We start with the most trivial implementation and progressively add new features:

Article Description
Logging a constant message This is the simplest possible implementation of logging.
Adding the method name Instead of logging a constant, generic message, we now include the method name in the message.
Adding the parameter values We now add the parameter values and the return value to the message.
Using ILogger Instead of using Console.WriteLine, we inject an ILogger into the target type using dependency injection.
ILogger without dependency injection Instead of using dependency injection, we expect the source code to contain an ILogger field and report errors if it does not.
Adding logging to many methods So far, we have manually added a custom attribute to each method. In this example, we show how to target several methods programmatically using compile-time code queries.
Redacting sensitive data Passwords and other sensitive data are excluded from the log.
Avoiding infinite recursions Adds a recursion guard to avoid infinite recursions due to logging.