A code block should not contain too many logging statements of a specific level.

Why is this an issue?

Excessive logging within a code block can lead to several problems:

Only the logging statements that are directly within the code block will be counted, and any logging statements within nested blocks will count towards their own. For example consider the snippet below:

void MyMethod(List<MyObject> items)
{
    logger.Debug("The operation started");
    foreach(var item in items)
    {
        logger.Debug($"Evaluating {item.Name}");
        var result = Evaluate(item);
        logger.Debug($"Evaluating resulted in {result}");
    }
    logger.Debug("The operation ended");
}

The rule will count 2 logging statements that are within the method block (namely logger.Debug("The operation started") and logger.Debug("The operation ended")). Any statements within nested blocks, such as the foreach block will be counted separately. The rule considers the log level of the calls, as follows:

The most popular logging frameworks are supported:

How to fix it

Reduce the number of specific logging level calls within the code block by identifying and selecting essential log statements with relevant information, necessary for understanding the flow of execution or diagnosing issues.

Code examples

Noncompliant code example

With the default Information threshold parameter value 2:

void MyMethod(List<MyObject> items)
{
    logger.Debug("The operation started");
    foreach(var item in items)
    {
        logger.Information($"Evaluating {item.Name}"); // Noncompliant
        var result = Evaluate(item);
        logger.Information($"Evaluating resulted in {result}"); // Secondary 1
        if (item.Name is string.Empty)
        {
            logger.Error("Invalid item name");
        }
        logger.Information("End item evaluation"); // Secondary 2
    }
    logger.Debug("The operation ended");
}

Compliant solution

With the default Information threshold parameter value 2:

void MyMethod(List<MyObject> items)
{
    logger.Debug("The operation started");
    foreach(var item in items)
    {
        logger.Information($"Evaluating {item.Name}");
        var result = Evaluate(item);
        if (item.Name is string.Empty)
        {
            logger.Error("Invalid item name");
        }
        logger.Information($"End item evaluation with result: {result}");
    }
    logger.Debug("The operation ended");
}

Resources

Documentation