All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S1312.html Maven / Gradle / Ivy

There is a newer version: 9.30.0.95878
Show newest version

Why is this an issue?

Regardless of the logging framework in use (Microsoft.Extension.Logging, Serilog, Log4net, NLog, …​​), logger fields should be:

  • private: this restricts access to the logger from outside the enclosing type (class, struct, record…​). Using any other access modifier would allow other types to use the logger to log messages in the type where it’s defined.
  • static: making the logger field static will ensure that the lifetime of the object doesn’t depend on the lifetime of the instance of the enclosing type.
  • readonly: marking the field as readonly will prevent modifications to the reference of the logger. This ensures that the reference to the logger remains consistent and doesn’t get accidentally reassigned during the lifetime of the enclosing type.

This rule should be activated when Service Locator Design pattern is followed in place of Dependency Injection for logging.

The rule supports the most popular logging frameworks:

How to fix it

Make the logging field {private static readonly}.

Noncompliant code example

public Logger logger;

Compliant solution

private static readonly Logger logger;

Resources

Documentation

Articles & blog posts





© 2015 - 2024 Weber Informatics LLC | Privacy Policy