In software development, logs serve as a record of events within an application, providing crucial insights for debugging. When logging, it is
essential to ensure that the logs are:
- easily accessible
- uniformly formatted for readability
- properly recorded
- securely logged when dealing with sensitive data
Those requirements are not met if a program directly writes to the standard outputs (e.g., System.out, System.err). That is why defining and using
a dedicated logger is highly recommended.
Code examples
The following noncompliant code:
class MyClass {
public void doSomething() {
System.out.println("My Message"); // Noncompliant, output directly to System.out without a logger
}
}
Could be replaced by:
import java.util.logging.Logger;
class MyClass {
Logger logger = Logger.getLogger(getClass().getName());
public void doSomething() {
// ...
logger.info("My Message"); // Compliant, output via logger
// ...
}
}