1

I wanna use ArchUnit to enforce usage only SLF4J logging framework and avoid simple System.out calls. Also I would like to avoid any other logging frameworks for using. How can I implement the such check?

Currently I write this test

class EnforceSlf4JLoggingTest {

    private final JavaClasses importedClasses = new ClassFileImporter()
            .withImportOption(new ImportOption.DoNotIncludeTests())
            .importPackages("... my packages ...");

    @Test
    public void classesShouldNotUseJavaUtilLogging() {
        NO_CLASSES_SHOULD_USE_JAVA_UTIL_LOGGING.check(importedClasses);
    }

    @Test
    public void classesShouldNotUseSystemOutLogging() {
        noClasses()
                .should()
                .dependOnClassesThat()
                .belongToAnyOf(java.lang.System.class)
                .because("use SLF4J instead")
                .check(importedClasses);
    }
}

but it doesn't actually enforce SLF4J usage but only restrict java.unit.logging usage and prevent of having dependency to java.lang.System class (where actually System.out constant is located).

Whether is more elegant solution of my case?

Andriy Kryvtsun
  • 2,766
  • 1
  • 22
  • 32
  • " I would like to avoid any other logging frameworks" SLF4J is not a logging framework. It's just a standardized API for logging frameworks. You still need an implementation based on an actualy logging framework such as JUL, Log4J or Logback... – Puce Mar 16 '21 at 12:54

1 Answers1

0

There is no a simple way to avoid usage any other loggig systems beside of SLF4J but it's possible to use this ArchUnit check template

ArchRuleDefinition.noClasses()
  .should().dependOnClassesThat()
  .resideInAnyPackage(
    "java.util.logging..", 
    "org.apache.logging.."
  ).as("Please only depend on SLF4J as a logging framework");

In the section resideInAnyPackage should be specified packages of different logging systems have to be avoided.

Also, rule

com.tngtech.archunit.library.GeneralCodingRules.NO_CLASSES_SHOULD_ACCESS_STANDARD_STREAMS 

has to be used to check absents any plain System.out, System.err and printStackTrace calls in code.

Andriy Kryvtsun
  • 2,766
  • 1
  • 22
  • 32