It is a well-established convention to name each logger after its enclosing type. This rule raises an issue when the convention is not
respected.
class EnclosingType
{
private readonly ILogger logger;
public EnclosingType(ILoggerFactory loggerFactory)
{
logger = loggerFactory.CreateLogger<AnotherType>(); // Noncompliant
logger = loggerFactory.CreateLogger<EnclosingType>(); // Compliant
}
}
Not following such a convention can result in confusion and logging misconfiguration.
For example, the person configuring the log may attempt to change the logging behavior for the MyNamespace.EnclosingType
type, by
overriding defaults for the logger named after that type.
{
"Logging": {
"LogLevel": {
"Default": "Error",
"MyNamespace.EnclosingType": "Debug"
}
}
}
However, if the convention is not in place, the override would not affect logs from MyNamespace.EnclosingType
, since they are made via
a logger with a different name.
Moreover, using the same logger name for multiple types prevents the granular configuration of each type’s logger, since there is no way to
distinguish them in configuration.
The rule targets the following logging frameworks: * Microsoft
Extensions Logging * Apache log4net * NLog
Exceptions
The rule doesn’t raise issues when custom handling of logging names is in place, and the logger name is not derived from a Type
.
class EnclosingType
{
private readonly ILogger logger;
EnclosingType(ILoggerFactory loggerFactory)
{
logger = loggerFactory.CreateLogger("My cross-type logging category"); // Compliant
logger = loggerFactory.CreateLogger(AComplexLogicToFindTheRightType()); // Compliant
}
}