├── .nvmrc ├── .java-version ├── .github ├── FUNDING.yml └── workflows │ └── build.yml ├── settings.gradle.kts ├── .gitattributes ├── gradle ├── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties └── libs.versions.toml ├── renovate.json ├── gradle.properties ├── package.json ├── src ├── main │ └── java │ │ └── jp │ │ └── skypencil │ │ └── errorprone │ │ └── slf4j │ │ ├── Consts.java │ │ ├── Slf4jLoggerShouldBeFinal.java │ │ ├── Slf4jFormatShouldBeConst.java │ │ ├── Slf4jLoggerShouldBePrivate.java │ │ ├── Slf4jSignOnlyFormat.java │ │ ├── Slf4jLoggerShouldBeNonStatic.java │ │ ├── Slf4jDoNotLogMessageOfExceptionExplicitly.java │ │ ├── Slf4jPlaceholderMismatch.java │ │ └── Slf4jIllegalPassedClass.java └── test │ └── java │ └── jp │ └── skypencil │ └── errorprone │ └── slf4j │ ├── Slf4JLoggerShouldBeFinalTest.java │ ├── Slf4jDoNotLogMessageOfExceptionExplicitlyTest.java │ ├── Slf4JLoggerShouldBeNonStaticTest.java │ ├── Slf4jFormatShouldBeConstTest.java │ ├── Slf4JLoggerShouldBePrivateTest.java │ ├── Slf4jSignOnlyFormatTest.java │ ├── Slf4jPlaceholderMismatchTest.java │ └── Slf4jIllegalPassedClassTest.java ├── gradlew.bat ├── README.md ├── .gitignore ├── gradlew └── LICENSE /.nvmrc: -------------------------------------------------------------------------------- 1 | 20 2 | -------------------------------------------------------------------------------- /.java-version: -------------------------------------------------------------------------------- 1 | 21 2 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [KengoTODA] 2 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "errorprone-slf4j" 2 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | gradlew linguist-generated=true 2 | gradlew.bat linguist-generated=true 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KengoTODA/errorprone-slf4j/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.1-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "packageRules": [ 4 | { 5 | "matchUpdateTypes": ["minor", "patch"], 6 | "matchCurrentVersion": "!/^0/", 7 | "automerge": true 8 | } 9 | ], 10 | "extends": [ 11 | "config:base" 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.caching=true 2 | org.gradle.configureondemand=true 3 | org.gradle.jvmargs=-XX:+HeapDumpOnOutOfMemoryError -Xmx1G --add-exports jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED 4 | org.gradle.parallel=true 5 | version=1.0.0-SNAPSHOT -------------------------------------------------------------------------------- /gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | [versions] 2 | errorprone = "2.38.0" 3 | 4 | [libraries] 5 | errorprone-check-api = { module = "com.google.errorprone:error_prone_check_api", version.ref = "errorprone" } 6 | errorprone-core = { module = "com.google.errorprone:error_prone_core", version.ref = "errorprone" } 7 | errorprone-test-helpers = { module = "com.google.errorprone:error_prone_test_helpers", version.ref = "errorprone" } 8 | 9 | [plugins] 10 | spotless = { id = "com.diffplug.spotless", version = "7.0.4" } 11 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "errorprone-slf4j", 3 | "repository": { 4 | "type": "git", 5 | "url": "git+https://github.com/KengoTODA/errorprone-slf4j.git" 6 | }, 7 | "author": "Kengo TODA", 8 | "bugs": { 9 | "url": "https://github.com/KengoTODA/errorprone-slf4j/issues" 10 | }, 11 | "engines": { 12 | "node": "^20.0.0" 13 | }, 14 | "homepage": "https://github.com/KengoTODA/errorprone-slf4j#readme", 15 | "devDependencies": { 16 | "@semantic-release/github": "^9.0.0", 17 | "gradle-semantic-release-plugin": "^1.8.0", 18 | "semantic-release": "^22.0.0" 19 | }, 20 | "release": { 21 | "branches": [ 22 | "master" 23 | ], 24 | "plugins": [ 25 | "gradle-semantic-release-plugin", 26 | "@semantic-release/commit-analyzer", 27 | "@semantic-release/release-notes-generator", 28 | [ 29 | "@semantic-release/github", 30 | { 31 | "assets": [ 32 | { 33 | "path": "build/libs/*.jar" 34 | } 35 | ] 36 | } 37 | ] 38 | ] 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/jp/skypencil/errorprone/slf4j/Consts.java: -------------------------------------------------------------------------------- 1 | package jp.skypencil.errorprone.slf4j; 2 | 3 | import com.google.common.collect.ImmutableSet; 4 | import com.google.errorprone.matchers.Matcher; 5 | import com.google.errorprone.matchers.Matchers; 6 | import com.google.errorprone.matchers.method.MethodMatchers; 7 | import com.google.errorprone.matchers.method.MethodMatchers.MethodNameMatcher; 8 | import com.sun.source.tree.ExpressionTree; 9 | import com.sun.source.tree.VariableTree; 10 | import java.util.regex.Pattern; 11 | 12 | class Consts { 13 | private static final String FQN_SLF4J_LOGGER = "org.slf4j.Logger"; 14 | private static final String FQN_SLF4J_MARKER = "org.slf4j.Marker"; 15 | static final ImmutableSet TARGET_METHOD_NAMES = 16 | ImmutableSet.of("trace", "debug", "info", "warn", "error"); 17 | 18 | static final MethodNameMatcher IS_LOGGING_METHOD = 19 | MethodMatchers.instanceMethod() 20 | .onDescendantOf(FQN_SLF4J_LOGGER) 21 | .withNameMatching(Pattern.compile(String.join("|", TARGET_METHOD_NAMES))); 22 | 23 | static final Matcher SLF4J_LOGGER = Matchers.isSubtypeOf(FQN_SLF4J_LOGGER); 24 | static final Matcher IS_MARKER = Matchers.isSubtypeOf(FQN_SLF4J_MARKER); 25 | 26 | private Consts() {} 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/jp/skypencil/errorprone/slf4j/Slf4JLoggerShouldBeFinalTest.java: -------------------------------------------------------------------------------- 1 | package jp.skypencil.errorprone.slf4j; 2 | 3 | import com.google.errorprone.BugCheckerRefactoringTestHelper; 4 | import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode; 5 | import com.google.errorprone.bugpatterns.BugChecker; 6 | import java.io.IOException; 7 | import org.junit.Test; 8 | 9 | public class Slf4JLoggerShouldBeFinalTest { 10 | @Test 11 | public void testRefactoringStaticLogger() throws IOException { 12 | BugChecker checker = new Slf4jLoggerShouldBeFinal(); 13 | BugCheckerRefactoringTestHelper helper = 14 | BugCheckerRefactoringTestHelper.newInstance(checker, getClass()); 15 | helper 16 | .addInputLines( 17 | "NonFinalLogger.java", 18 | "import org.slf4j.Logger;\n" 19 | + "import org.slf4j.LoggerFactory;\n" 20 | + "\n" 21 | + "public class NonFinalLogger {\n" 22 | + " private Logger logger = LoggerFactory.getLogger(getClass());\n" 23 | + "}") 24 | .addOutputLines( 25 | "NonFinalLogger.java", 26 | "import org.slf4j.Logger;\n" 27 | + "import org.slf4j.LoggerFactory;\n" 28 | + "\n" 29 | + "public class NonFinalLogger {\n" 30 | + " private final Logger logger = LoggerFactory.getLogger(getClass());\n" 31 | + "}\n" 32 | + "") 33 | .doTest(TestMode.TEXT_MATCH); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/test/java/jp/skypencil/errorprone/slf4j/Slf4jDoNotLogMessageOfExceptionExplicitlyTest.java: -------------------------------------------------------------------------------- 1 | package jp.skypencil.errorprone.slf4j; 2 | 3 | import com.google.errorprone.CompilationTestHelper; 4 | import java.io.IOException; 5 | import org.junit.Test; 6 | 7 | public class Slf4jDoNotLogMessageOfExceptionExplicitlyTest { 8 | @Test 9 | public void test() throws IOException { 10 | CompilationTestHelper helper = 11 | CompilationTestHelper.newInstance( 12 | Slf4jDoNotLogMessageOfExceptionExplicitly.class, getClass()); 13 | helper 14 | .addSourceLines( 15 | "WithManualMessage.java", 16 | "import org.slf4j.Logger;\n" 17 | + "import org.slf4j.LoggerFactory;\n" 18 | + "\n" 19 | + "public class WithManualMessage {\n" 20 | + " private Logger logger = LoggerFactory.getLogger(WithManualMessage.class);\n" 21 | + " void method(Exception e) {\n" 22 | + " logger.info(\"Exception given\", e);\n" 23 | + " // BUG: Diagnostic contains: Do not log message returned from Throwable#getMessage and Throwable#getLocalizedMessage\n" 24 | + " logger.info(\"Message of given exception: {}\", e.getMessage());\n" 25 | + " // BUG: Diagnostic contains: Do not log message returned from Throwable#getMessage and Throwable#getLocalizedMessage\n" 26 | + " logger.info(\"Message of given exception: {}\", e.getLocalizedMessage());\n" 27 | + " }\n" 28 | + "}") 29 | .doTest(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: ['master'] 4 | pull_request: 5 | 6 | permissions: 7 | checks: write # for SonarQube 8 | contents: write # for semantic-release/github 9 | issues: write # fir semantic-release/github 10 | statuses: read # for SonarQube 11 | pull-requests: write # for SonarQube and semantic-release/github 12 | 13 | jobs: 14 | build: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v4 18 | with: 19 | fetch-depth: 0 20 | - uses: actions/setup-java@v4 21 | with: 22 | distribution: 'microsoft' 23 | java-version-file: '.java-version' 24 | - uses: actions/setup-node@v4 25 | with: 26 | node-version-file: '.nvmrc' 27 | cache: 'npm' 28 | - name: Setup Gradle with wrapper validation and dependency graphs 29 | uses: gradle/actions/setup-gradle@v4 30 | with: 31 | validate-wrappers: true 32 | dependency-graph: generate-and-submit 33 | - run: | 34 | ./gradlew build ${SONAR_TOKEN:+sonar} 35 | rm build/libs/*.jar 36 | npm ci 37 | npx semantic-release 38 | env: 39 | SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} 40 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 41 | ORG_GRADLE_PROJECT_sonatypeUsername: ${{ secrets.SONATYPE_USERNAME }} 42 | ORG_GRADLE_PROJECT_sonatypePassword: ${{ secrets.SONATYPE_PASSWORD }} 43 | ORG_GRADLE_PROJECT_signingKey: ${{ secrets.SIGNING_KEY }} 44 | ORG_GRADLE_PROJECT_signingPassword: ${{ secrets.SIGNING_PASSWORD }} 45 | - uses: actions/upload-artifact@v4 46 | if: failure() 47 | with: 48 | name: reports 49 | path: build/reports 50 | -------------------------------------------------------------------------------- /src/main/java/jp/skypencil/errorprone/slf4j/Slf4jLoggerShouldBeFinal.java: -------------------------------------------------------------------------------- 1 | package jp.skypencil.errorprone.slf4j; 2 | 3 | import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; 4 | import static com.google.errorprone.matchers.Matchers.allOf; 5 | import static com.google.errorprone.matchers.Matchers.hasModifier; 6 | import static com.google.errorprone.matchers.Matchers.isField; 7 | import static com.google.errorprone.matchers.Matchers.not; 8 | import static jp.skypencil.errorprone.slf4j.Consts.SLF4J_LOGGER; 9 | 10 | import com.google.auto.service.AutoService; 11 | import com.google.errorprone.BugPattern; 12 | import com.google.errorprone.BugPattern.LinkType; 13 | import com.google.errorprone.VisitorState; 14 | import com.google.errorprone.bugpatterns.BugChecker; 15 | import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; 16 | import com.google.errorprone.fixes.SuggestedFixes; 17 | import com.google.errorprone.matchers.Description; 18 | import com.sun.source.tree.VariableTree; 19 | import javax.lang.model.element.Modifier; 20 | 21 | @BugPattern( 22 | altNames = {"PreferFinalSlf4jLogger"}, 23 | summary = "Logger field should be final", 24 | tags = {"SLF4J"}, 25 | link = "https://github.com/KengoTODA/findbugs-slf4j#slf4j_logger_should_be_final", 26 | linkType = LinkType.CUSTOM, 27 | severity = WARNING) 28 | @AutoService(BugChecker.class) 29 | public class Slf4jLoggerShouldBeFinal extends BugChecker implements VariableTreeMatcher { 30 | private static final long serialVersionUID = -5127926153475887075L; 31 | 32 | @Override 33 | public Description matchVariable(VariableTree tree, VisitorState state) { 34 | if (allOf(isField(), SLF4J_LOGGER, not(hasModifier(Modifier.FINAL))).matches(tree, state)) { 35 | return buildDescription(tree) 36 | .addFix(SuggestedFixes.addModifiers(tree, state, Modifier.FINAL)) 37 | .build(); 38 | } 39 | return Description.NO_MATCH; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/jp/skypencil/errorprone/slf4j/Slf4jFormatShouldBeConst.java: -------------------------------------------------------------------------------- 1 | package jp.skypencil.errorprone.slf4j; 2 | 3 | import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; 4 | import static jp.skypencil.errorprone.slf4j.Consts.IS_MARKER; 5 | 6 | import com.google.auto.service.AutoService; 7 | import com.google.errorprone.BugPattern; 8 | import com.google.errorprone.BugPattern.LinkType; 9 | import com.google.errorprone.VisitorState; 10 | import com.google.errorprone.bugpatterns.BugChecker; 11 | import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; 12 | import com.google.errorprone.matchers.Description; 13 | import com.google.errorprone.util.ASTHelpers; 14 | import com.sun.source.tree.ExpressionTree; 15 | import com.sun.source.tree.MethodInvocationTree; 16 | 17 | @BugPattern( 18 | altNames = {"FormatShouldBeConst"}, 19 | summary = "Format of SLF4J logging should be constant value", 20 | tags = {"SLF4J"}, 21 | link = "https://github.com/KengoTODA/findbugs-slf4j#slf4j_format_should_be_const", 22 | linkType = LinkType.CUSTOM, 23 | severity = ERROR) 24 | @AutoService(BugChecker.class) 25 | public class Slf4jFormatShouldBeConst extends BugChecker implements MethodInvocationTreeMatcher { 26 | private static final long serialVersionUID = 3271269614137732880L; 27 | 28 | @Override 29 | public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { 30 | if (!Consts.IS_LOGGING_METHOD.matches(tree, state)) { 31 | return Description.NO_MATCH; 32 | } 33 | 34 | int formatIndex = IS_MARKER.matches(tree.getArguments().get(0), state) ? 1 : 0; 35 | 36 | ExpressionTree expression = tree.getArguments().get(formatIndex); 37 | Object constValue = ASTHelpers.constValue(expression); 38 | if (constValue != null) { 39 | return Description.NO_MATCH; 40 | } 41 | 42 | String message = 43 | String.format( 44 | "SLF4J logging format should be constant value, but it is \'%s\'", 45 | state.getSourceForNode(expression)); 46 | return buildDescription(tree).setMessage(message).build(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/jp/skypencil/errorprone/slf4j/Slf4jLoggerShouldBePrivate.java: -------------------------------------------------------------------------------- 1 | package jp.skypencil.errorprone.slf4j; 2 | 3 | import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; 4 | import static com.google.errorprone.matchers.Matchers.allOf; 5 | import static com.google.errorprone.matchers.Matchers.hasModifier; 6 | import static com.google.errorprone.matchers.Matchers.isField; 7 | import static com.google.errorprone.matchers.Matchers.not; 8 | import static jp.skypencil.errorprone.slf4j.Consts.SLF4J_LOGGER; 9 | 10 | import com.google.auto.service.AutoService; 11 | import com.google.errorprone.BugPattern; 12 | import com.google.errorprone.BugPattern.LinkType; 13 | import com.google.errorprone.VisitorState; 14 | import com.google.errorprone.bugpatterns.BugChecker; 15 | import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; 16 | import com.google.errorprone.fixes.SuggestedFix; 17 | import com.google.errorprone.fixes.SuggestedFixes; 18 | import com.google.errorprone.matchers.Description; 19 | import com.sun.source.tree.VariableTree; 20 | import javax.lang.model.element.Modifier; 21 | 22 | @BugPattern( 23 | altNames = {"DoNotPublishSlf4jLogger"}, 24 | summary = "Do not publish Logger field, it should be private", 25 | tags = {"SLF4J"}, 26 | link = "https://github.com/KengoTODA/findbugs-slf4j#slf4j_logger_should_be_private", 27 | linkType = LinkType.CUSTOM, 28 | severity = WARNING) 29 | @AutoService(BugChecker.class) 30 | public class Slf4jLoggerShouldBePrivate extends BugChecker implements VariableTreeMatcher { 31 | private static final long serialVersionUID = 3718668951312958622L; 32 | 33 | @Override 34 | public Description matchVariable(VariableTree tree, VisitorState state) { 35 | if (allOf(isField(), SLF4J_LOGGER, not(hasModifier(Modifier.PRIVATE))).matches(tree, state)) { 36 | SuggestedFix.Builder builder = SuggestedFix.builder(); 37 | SuggestedFixes.addModifiers(tree, state, Modifier.PRIVATE).ifPresent(builder::merge); 38 | SuggestedFixes.removeModifiers(tree, state, Modifier.PUBLIC, Modifier.PROTECTED) 39 | .ifPresent(builder::merge); 40 | return buildDescription(tree).addFix(builder.build()).build(); 41 | } 42 | return Description.NO_MATCH; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/jp/skypencil/errorprone/slf4j/Slf4jSignOnlyFormat.java: -------------------------------------------------------------------------------- 1 | package jp.skypencil.errorprone.slf4j; 2 | 3 | import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; 4 | import static jp.skypencil.errorprone.slf4j.Consts.IS_MARKER; 5 | 6 | import com.google.auto.service.AutoService; 7 | import com.google.errorprone.BugPattern; 8 | import com.google.errorprone.BugPattern.LinkType; 9 | import com.google.errorprone.VisitorState; 10 | import com.google.errorprone.bugpatterns.BugChecker; 11 | import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; 12 | import com.google.errorprone.matchers.Description; 13 | import com.google.errorprone.util.ASTHelpers; 14 | import com.sun.source.tree.ExpressionTree; 15 | import com.sun.source.tree.MethodInvocationTree; 16 | 17 | @BugPattern( 18 | altNames = {"SignOnlyFormat"}, 19 | summary = "To make log readable, log format should contain not only sign but also texts", 20 | tags = {"SLF4J"}, 21 | link = "https://github.com/KengoTODA/findbugs-slf4j#slf4j_sign_only_format", 22 | linkType = LinkType.CUSTOM, 23 | severity = ERROR) 24 | @AutoService(BugChecker.class) 25 | public class Slf4jSignOnlyFormat extends BugChecker implements MethodInvocationTreeMatcher { 26 | private static final long serialVersionUID = 3271269614137732880L; 27 | 28 | @Override 29 | public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { 30 | if (!Consts.IS_LOGGING_METHOD.matches(tree, state)) { 31 | return Description.NO_MATCH; 32 | } 33 | 34 | int formatIndex = IS_MARKER.matches(tree.getArguments().get(0), state) ? 1 : 0; 35 | 36 | ExpressionTree expression = tree.getArguments().get(formatIndex); 37 | Object constValue = ASTHelpers.constValue(expression); 38 | if (constValue == null) { 39 | return Description.NO_MATCH; 40 | } 41 | String format = constValue.toString(); 42 | if (verifyFormat(format)) { 43 | return Description.NO_MATCH; 44 | } 45 | String message = 46 | String.format( 47 | "SLF4J logging format should contain non-sign text, but it is \'%s\'", format); 48 | return buildDescription(tree).setMessage(message).build(); 49 | } 50 | 51 | private static boolean verifyFormat(String formatString) { 52 | return formatString.codePoints().anyMatch(Character::isLetter); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/jp/skypencil/errorprone/slf4j/Slf4jLoggerShouldBeNonStatic.java: -------------------------------------------------------------------------------- 1 | package jp.skypencil.errorprone.slf4j; 2 | 3 | import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION; 4 | import static com.google.errorprone.matchers.Matchers.allOf; 5 | import static com.google.errorprone.matchers.Matchers.isField; 6 | import static com.google.errorprone.matchers.Matchers.isStatic; 7 | import static jp.skypencil.errorprone.slf4j.Consts.SLF4J_LOGGER; 8 | 9 | import com.google.auto.service.AutoService; 10 | import com.google.common.base.CaseFormat; 11 | import com.google.errorprone.BugPattern; 12 | import com.google.errorprone.BugPattern.LinkType; 13 | import com.google.errorprone.VisitorState; 14 | import com.google.errorprone.bugpatterns.BugChecker; 15 | import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; 16 | import com.google.errorprone.fixes.SuggestedFix; 17 | import com.google.errorprone.fixes.SuggestedFixes; 18 | import com.google.errorprone.matchers.Description; 19 | import com.sun.source.tree.VariableTree; 20 | import java.util.Optional; 21 | import javax.lang.model.element.Modifier; 22 | 23 | @BugPattern( 24 | altNames = {"DoNotUseStaticSlf4jLogger"}, 25 | summary = "Do not use static Logger field, use non-static one instead", 26 | tags = {"SLF4J"}, 27 | link = "https://github.com/KengoTODA/findbugs-slf4j#slf4j_logger_should_be_non_static", 28 | linkType = LinkType.CUSTOM, 29 | severity = SUGGESTION) 30 | @AutoService(BugChecker.class) 31 | public class Slf4jLoggerShouldBeNonStatic extends BugChecker implements VariableTreeMatcher { 32 | private static final long serialVersionUID = 2656759159827947106L; 33 | 34 | @Override 35 | public Description matchVariable(VariableTree tree, VisitorState state) { 36 | if (allOf(isField(), SLF4J_LOGGER, isStatic()).matches(tree, state)) { 37 | SuggestedFix.Builder builder = SuggestedFix.builder(); 38 | SuggestedFixes.removeModifiers(tree, state, Modifier.STATIC).ifPresent(builder::merge); 39 | suggestRename(tree, state).ifPresent(builder::merge); 40 | 41 | return buildDescription(tree).addFix(builder.build()).build(); 42 | } 43 | return Description.NO_MATCH; 44 | } 45 | 46 | private static Optional suggestRename(VariableTree tree, VisitorState state) { 47 | String name = tree.getName().toString(); 48 | String formatted = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name); 49 | if (name.equals(formatted)) { 50 | return Optional.empty(); 51 | } 52 | return Optional.of(SuggestedFixes.renameVariable(tree, formatted, state)); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/test/java/jp/skypencil/errorprone/slf4j/Slf4JLoggerShouldBeNonStaticTest.java: -------------------------------------------------------------------------------- 1 | package jp.skypencil.errorprone.slf4j; 2 | 3 | import com.google.errorprone.BugCheckerRefactoringTestHelper; 4 | import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode; 5 | import com.google.errorprone.bugpatterns.BugChecker; 6 | import java.io.IOException; 7 | import org.junit.Test; 8 | 9 | public class Slf4JLoggerShouldBeNonStaticTest { 10 | @Test 11 | public void testRefactoringStaticLogger() throws IOException { 12 | BugChecker checker = new Slf4jLoggerShouldBeNonStatic(); 13 | BugCheckerRefactoringTestHelper helper = 14 | BugCheckerRefactoringTestHelper.newInstance(checker, getClass()); 15 | helper 16 | .addInputLines( 17 | "StaticLogger.java", 18 | "import org.slf4j.Logger;\n" 19 | + "import org.slf4j.LoggerFactory;\n" 20 | + "\n" 21 | + "public class StaticLogger {\n" 22 | + " private static Logger LOGGER = LoggerFactory.getLogger(\"static\");\n" 23 | + "}") 24 | .addOutputLines( 25 | "StaticLogger.java", 26 | "import org.slf4j.Logger;\n" 27 | + "import org.slf4j.LoggerFactory;\n" 28 | + "\n" 29 | + "public class StaticLogger {\n" 30 | + " private Logger logger = LoggerFactory.getLogger(\"static\");\n" 31 | + "}\n" 32 | + "") 33 | .doTest(TestMode.TEXT_MATCH); 34 | } 35 | 36 | @Test 37 | public void testRefactoringWithAnnotation() throws IOException { 38 | BugChecker checker = new Slf4jLoggerShouldBeNonStatic(); 39 | BugCheckerRefactoringTestHelper helper = 40 | BugCheckerRefactoringTestHelper.newInstance(checker, getClass()); 41 | helper 42 | .addInputLines( 43 | "StaticLogger.java", 44 | "import org.slf4j.Logger;\n" 45 | + "import org.slf4j.LoggerFactory;\n" 46 | + "\n" 47 | + "public class StaticLogger {\n" 48 | + " private static Logger LOGGER = LoggerFactory.getLogger(\"static\");\n" 49 | + "}") 50 | .addOutputLines( 51 | "StaticLogger.java", 52 | "import org.slf4j.Logger;\n" 53 | + "import org.slf4j.LoggerFactory;\n" 54 | + "\n" 55 | + "public class StaticLogger {\n" 56 | + " private Logger logger = LoggerFactory.getLogger(\"static\");\n" 57 | + "}\n" 58 | + "") 59 | .doTest(TestMode.TEXT_MATCH); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/jp/skypencil/errorprone/slf4j/Slf4jDoNotLogMessageOfExceptionExplicitly.java: -------------------------------------------------------------------------------- 1 | package jp.skypencil.errorprone.slf4j; 2 | 3 | import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; 4 | 5 | import com.google.auto.service.AutoService; 6 | import com.google.errorprone.BugPattern; 7 | import com.google.errorprone.BugPattern.LinkType; 8 | import com.google.errorprone.VisitorState; 9 | import com.google.errorprone.bugpatterns.BugChecker; 10 | import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; 11 | import com.google.errorprone.matchers.Description; 12 | import com.sun.source.tree.MethodInvocationTree; 13 | import com.sun.tools.javac.tree.JCTree.JCFieldAccess; 14 | import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; 15 | import java.util.Optional; 16 | import java.util.function.Predicate; 17 | 18 | @BugPattern( 19 | altNames = {"ManuallyProvidedMessage"}, 20 | summary = 21 | "Do not log message returned from Throwable#getMessage and Throwable#getLocalizedMessage", 22 | tags = {"SLF4J"}, 23 | link = "https://github.com/KengoTODA/findbugs-slf4j#slf4j_manually_provided_message", 24 | linkType = LinkType.CUSTOM, 25 | severity = ERROR) 26 | @AutoService(BugChecker.class) 27 | public class Slf4jDoNotLogMessageOfExceptionExplicitly extends BugChecker 28 | implements MethodInvocationTreeMatcher { 29 | 30 | private static final long serialVersionUID = 7903613628689308557L; 31 | private static final Predicate MESSAGE_GETTER = "getMessage"::equals; 32 | private static final Predicate LOCALIZED_MESSAGE_GETTER = "getLocalizedMessage"::equals; 33 | private static final Predicate THROWABLE = "java.lang.Throwable"::equals; 34 | 35 | @Override 36 | public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { 37 | if (!Consts.IS_LOGGING_METHOD.matches(tree, state)) { 38 | return Description.NO_MATCH; 39 | } 40 | 41 | Optional problem = 42 | tree.getArguments().stream() 43 | .filter(arg -> arg.getClass().isAssignableFrom(JCMethodInvocation.class)) 44 | .map(JCMethodInvocation.class::cast) 45 | .map(arg -> arg.meth) 46 | .filter(meth -> meth.getClass().isAssignableFrom(JCFieldAccess.class)) 47 | .map(JCFieldAccess.class::cast) 48 | .filter( 49 | meth -> MESSAGE_GETTER.or(LOCALIZED_MESSAGE_GETTER).test(meth.sym.name.toString())) 50 | .filter(meth -> THROWABLE.test(meth.sym.owner.toString())) 51 | .findFirst(); 52 | if (problem.isPresent()) { 53 | return buildDescription(tree) 54 | .setMessage( 55 | "Do not log message returned from Throwable#getMessage and Throwable#getLocalizedMessage. It is enough to provide throwable instance as the last argument, then binding will log its message.") 56 | .build(); 57 | } 58 | return Description.NO_MATCH; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH= 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /src/main/java/jp/skypencil/errorprone/slf4j/Slf4jPlaceholderMismatch.java: -------------------------------------------------------------------------------- 1 | package jp.skypencil.errorprone.slf4j; 2 | 3 | import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; 4 | import static com.google.errorprone.matchers.Matchers.isSubtypeOf; 5 | import static jp.skypencil.errorprone.slf4j.Consts.IS_MARKER; 6 | 7 | import com.google.auto.service.AutoService; 8 | import com.google.errorprone.BugPattern; 9 | import com.google.errorprone.BugPattern.LinkType; 10 | import com.google.errorprone.VisitorState; 11 | import com.google.errorprone.bugpatterns.BugChecker; 12 | import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; 13 | import com.google.errorprone.matchers.Description; 14 | import com.google.errorprone.util.ASTHelpers; 15 | import com.sun.source.tree.ExpressionTree; 16 | import com.sun.source.tree.MethodInvocationTree; 17 | import java.util.regex.Matcher; 18 | import java.util.regex.Pattern; 19 | 20 | @BugPattern( 21 | altNames = {"PlaceholderMismatch"}, 22 | summary = "Count of placeholder does not match with count of parameter", 23 | tags = {"SLF4J"}, 24 | link = "https://github.com/KengoTODA/findbugs-slf4j#slf4j_place_holder_mismatch", 25 | linkType = LinkType.CUSTOM, 26 | severity = ERROR) 27 | @AutoService(BugChecker.class) 28 | public class Slf4jPlaceholderMismatch extends BugChecker implements MethodInvocationTreeMatcher { 29 | 30 | private static final long serialVersionUID = 1442638758364703416L; 31 | private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("(.?)(\\\\\\\\)*\\{\\}"); 32 | 33 | @Override 34 | public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { 35 | if (!Consts.IS_LOGGING_METHOD.matches(tree, state)) { 36 | return Description.NO_MATCH; 37 | } 38 | 39 | java.util.List arguments = tree.getArguments(); 40 | int argumentSize = arguments.size() - 1; // -1 means 'formatString' is not parameter 41 | int formatIndex = 0; 42 | if (IS_MARKER.matches(arguments.get(0), state)) { 43 | argumentSize--; 44 | formatIndex = 1; 45 | } 46 | if (IS_THROWABLE.matches(arguments.get(arguments.size() - 1), state)) { 47 | argumentSize--; 48 | } 49 | if (argumentSize < 0) { 50 | return Description.NO_MATCH; 51 | } 52 | Object constant = ASTHelpers.constValue(tree.getArguments().get(formatIndex)); 53 | if (constant == null) { 54 | // format is not resolved at compile-phase 55 | return Description.NO_MATCH; 56 | } 57 | String format = constant.toString(); 58 | 59 | int placeholders = countPlaceholder(format); 60 | if (argumentSize != placeholders) { 61 | String message = 62 | String.format( 63 | "Count of placeholder (%d) does not match with count of parameter (%d)", 64 | placeholders, argumentSize); 65 | return buildDescription(tree).setMessage(message).build(); 66 | } 67 | return Description.NO_MATCH; 68 | } 69 | 70 | private static final com.google.errorprone.matchers.Matcher IS_THROWABLE = 71 | isSubtypeOf("java.lang.Throwable"); 72 | 73 | private static int countPlaceholder(String format) { 74 | Matcher matcher = PLACEHOLDER_PATTERN.matcher(format); 75 | int count = 0; 76 | while (matcher.find()) { 77 | if (!"\\".equals(matcher.group(1))) { 78 | ++count; 79 | } 80 | } 81 | return count; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/test/java/jp/skypencil/errorprone/slf4j/Slf4jFormatShouldBeConstTest.java: -------------------------------------------------------------------------------- 1 | package jp.skypencil.errorprone.slf4j; 2 | 3 | import com.google.errorprone.CompilationTestHelper; 4 | import org.junit.Before; 5 | import org.junit.Test; 6 | 7 | public class Slf4jFormatShouldBeConstTest { 8 | private CompilationTestHelper helper; 9 | 10 | @Before 11 | public void setup() { 12 | helper = CompilationTestHelper.newInstance(Slf4jFormatShouldBeConst.class, getClass()); 13 | } 14 | 15 | @Test 16 | public void testNonConstantFormat() { 17 | helper 18 | .addSourceLines( 19 | "NonConstantFormat.java", 20 | "import org.slf4j.Logger;\n" 21 | + "import org.slf4j.LoggerFactory;\n" 22 | + "\n" 23 | + "public class NonConstantFormat {\n" 24 | + " private final Logger logger = LoggerFactory.getLogger(getClass());\n" 25 | + " void method() {\n" 26 | + " // BUG: Diagnostic contains: SLF4J logging format should be constant value, but it is \'this + \" is me\"\'\n" 27 | + " logger.info(this + \" is me\");" 28 | + " }\n" 29 | + "}") 30 | .doTest(); 31 | } 32 | 33 | @Test 34 | public void testMarker() { 35 | helper 36 | .addSourceLines( 37 | "WithMarker.java", 38 | "import org.slf4j.Logger;\n" 39 | + "import org.slf4j.LoggerFactory;\n" 40 | + "import org.slf4j.MarkerFactory;\n" 41 | + "import org.slf4j.Marker;\n" 42 | + "\n" 43 | + "public class WithMarker {\n" 44 | + " private final Logger logger = LoggerFactory.getLogger(getClass());\n" 45 | + " private final Marker marker = MarkerFactory.getMarker(\"Sample\");\n" 46 | + " void method() {\n" 47 | + " logger.info(marker, \"I have one placeholder, one parameter and one marker instance. {}\", 1);" 48 | + " // BUG: Diagnostic contains: SLF4J logging format should be constant value, but it is \'this + \" is me\"\'\n" 49 | + " logger.info(marker, this + \" is me\");" 50 | + " }\n" 51 | + "}") 52 | .doTest(); 53 | } 54 | 55 | @Test 56 | public void testTernaryInStaticBlock() { 57 | helper 58 | .addSourceLines( 59 | "TernaryInStaticBlock.java", 60 | "import org.slf4j.Logger;\n" 61 | + "import org.slf4j.LoggerFactory;\n" 62 | + "\n" 63 | + "public class TernaryInStaticBlock {\n" 64 | + " public static boolean DEBUG = false;\n" 65 | + " public static final boolean DEBUG_FINAL = false;\n" 66 | + " private static final Logger logger = LoggerFactory.getLogger(TernaryInStaticBlock.class);\n" 67 | + "\n" 68 | + " static {\n" 69 | + " // BUG: Diagnostic contains: SLF4J logging format should be constant value, but it is '\"Debug mode \" + (DEBUG ? \"enabled.\" : \"disabled.\")'\n" 70 | + " logger.info(\"Debug mode \" + (DEBUG ? \"enabled.\" : \"disabled.\"));\n" 71 | + " logger.info(\"Debug mode \" + (DEBUG_FINAL ? \"enabled.\" : \"disabled.\"));\n" 72 | + " }\n" 73 | + "}\n") 74 | .doTest(); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/test/java/jp/skypencil/errorprone/slf4j/Slf4JLoggerShouldBePrivateTest.java: -------------------------------------------------------------------------------- 1 | package jp.skypencil.errorprone.slf4j; 2 | 3 | import com.google.errorprone.BugCheckerRefactoringTestHelper; 4 | import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode; 5 | import com.google.errorprone.bugpatterns.BugChecker; 6 | import java.io.IOException; 7 | import org.junit.Test; 8 | 9 | public class Slf4JLoggerShouldBePrivateTest { 10 | @Test 11 | public void testRefactoringPublicLogger() throws IOException { 12 | BugChecker checker = new Slf4jLoggerShouldBePrivate(); 13 | BugCheckerRefactoringTestHelper helper = 14 | BugCheckerRefactoringTestHelper.newInstance(checker, getClass()); 15 | helper 16 | .addInputLines( 17 | "PublicLogger.java", 18 | "import org.slf4j.Logger;\n" 19 | + "import org.slf4j.LoggerFactory;\n" 20 | + "\n" 21 | + "public class PublicLogger {\n" 22 | + " public Logger logger = LoggerFactory.getLogger(PublicLogger.class);\n" 23 | + "}") 24 | .addOutputLines( 25 | "PublicLogger.java", 26 | "import org.slf4j.Logger;\n" 27 | + "import org.slf4j.LoggerFactory;\n" 28 | + "\n" 29 | + "public class PublicLogger {\n" 30 | + " private Logger logger = LoggerFactory.getLogger(PublicLogger.class);\n" 31 | + "}\n" 32 | + "") 33 | .doTest(TestMode.TEXT_MATCH); 34 | } 35 | 36 | @Test 37 | public void testRefactoringProtectedLogger() throws IOException { 38 | BugChecker checker = new Slf4jLoggerShouldBePrivate(); 39 | BugCheckerRefactoringTestHelper helper = 40 | BugCheckerRefactoringTestHelper.newInstance(checker, getClass()); 41 | helper 42 | .addInputLines( 43 | "ProtectedLogger.java", 44 | "import org.slf4j.Logger;\n" 45 | + "import org.slf4j.LoggerFactory;\n" 46 | + "\n" 47 | + "public class ProtectedLogger {\n" 48 | + " protected Logger logger = LoggerFactory.getLogger(getClass());\n" 49 | + "}") 50 | .addOutputLines( 51 | "ProtectedLogger.java", 52 | "import org.slf4j.Logger;\n" 53 | + "import org.slf4j.LoggerFactory;\n" 54 | + "\n" 55 | + "public class ProtectedLogger {\n" 56 | + " private Logger logger = LoggerFactory.getLogger(getClass());\n" 57 | + "}\n" 58 | + "") 59 | .doTest(TestMode.TEXT_MATCH); 60 | } 61 | 62 | @Test 63 | public void testRefactoringPackagePrivateLogger() throws IOException { 64 | BugChecker checker = new Slf4jLoggerShouldBePrivate(); 65 | BugCheckerRefactoringTestHelper helper = 66 | BugCheckerRefactoringTestHelper.newInstance(checker, getClass()); 67 | helper 68 | .addInputLines( 69 | "PackagePrivateLogger.java", 70 | "import org.slf4j.Logger;\n" 71 | + "import org.slf4j.LoggerFactory;\n" 72 | + "\n" 73 | + "public class PackagePrivateLogger {\n" 74 | + " Logger logger = LoggerFactory.getLogger(getClass());\n" 75 | + "}") 76 | .addOutputLines( 77 | "PackagePrivateLogger.java", 78 | "import org.slf4j.Logger;\n" 79 | + "import org.slf4j.LoggerFactory;\n" 80 | + "\n" 81 | + "public class PackagePrivateLogger {\n" 82 | + " private Logger logger = LoggerFactory.getLogger(getClass());\n" 83 | + "}\n" 84 | + "") 85 | .doTest(TestMode.TEXT_MATCH); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/test/java/jp/skypencil/errorprone/slf4j/Slf4jSignOnlyFormatTest.java: -------------------------------------------------------------------------------- 1 | package jp.skypencil.errorprone.slf4j; 2 | 3 | import com.google.errorprone.CompilationTestHelper; 4 | import org.junit.Before; 5 | import org.junit.Test; 6 | 7 | public class Slf4jSignOnlyFormatTest { 8 | private CompilationTestHelper helper; 9 | 10 | @Before 11 | public void setup() { 12 | helper = CompilationTestHelper.newInstance(Slf4jSignOnlyFormat.class, getClass()); 13 | } 14 | 15 | @Test 16 | public void testPlaceholderOnly() { 17 | helper 18 | .addSourceLines( 19 | "PlaceholderOnly.java", 20 | "import org.slf4j.Logger;\n" 21 | + "import org.slf4j.LoggerFactory;\n" 22 | + "\n" 23 | + "public class PlaceholderOnly {\n" 24 | + " private final Logger logger = LoggerFactory.getLogger(getClass());\n" 25 | + " void method() {\n" 26 | + " // BUG: Diagnostic contains: SLF4J logging format should contain non-sign text, but it is \'{}, {}\'\n" 27 | + " logger.info(\"{}, {}\", 1, 2);" 28 | + " }\n" 29 | + "}") 30 | .doTest(); 31 | } 32 | 33 | @Test 34 | public void testNonConstantFormat() { 35 | helper 36 | .addSourceLines( 37 | "NonConstantFormat.java", 38 | "import org.slf4j.Logger;\n" 39 | + "import org.slf4j.LoggerFactory;\n" 40 | + "\n" 41 | + "public class NonConstantFormat {\n" 42 | + " private final Logger logger = LoggerFactory.getLogger(getClass());\n" 43 | + " void method() {\n" 44 | + " logger.info(this + \" is me\");" 45 | + " }\n" 46 | + "}") 47 | .doTest(); 48 | } 49 | 50 | @Test 51 | public void testMarker() { 52 | helper 53 | .addSourceLines( 54 | "WithMarker.java", 55 | "import org.slf4j.Logger;\n" 56 | + "import org.slf4j.LoggerFactory;\n" 57 | + "import org.slf4j.MarkerFactory;\n" 58 | + "import org.slf4j.Marker;\n" 59 | + "\n" 60 | + "public class WithMarker {\n" 61 | + " private final Logger logger = LoggerFactory.getLogger(getClass());\n" 62 | + " private final Marker marker = MarkerFactory.getMarker(\"Sample\");\n" 63 | + " void method() {\n" 64 | + " logger.info(marker, \"I have one placeholder, one parameter and one marker instance. {}\", 1);" 65 | + " // BUG: Diagnostic contains: SLF4J logging format should contain non-sign text, but it is \'{}: {}\'\n" 66 | + " logger.info(marker, \"{}: {}\", 1, 2);" 67 | + " }\n" 68 | + "}") 69 | .doTest(); 70 | } 71 | 72 | @Test 73 | public void testTernaryInStaticBlock() { 74 | helper 75 | .addSourceLines( 76 | "TernaryInStaticBlock.java", 77 | "import org.slf4j.Logger;\n" 78 | + "import org.slf4j.LoggerFactory;\n" 79 | + "\n" 80 | + "public class TernaryInStaticBlock {\n" 81 | + " public static boolean INDENT = true;\n" 82 | + " public static final boolean INDENT_FINAL = true;\n" 83 | + " private static final Logger logger = LoggerFactory.getLogger(TernaryInStaticBlock.class);\n" 84 | + "\n" 85 | + " static {\n" 86 | + " logger.info((INDENT ? \" \" : \"\") + \"{}\", 1);\n" 87 | + " // BUG: Diagnostic contains: SLF4J logging format should contain non-sign text, but it is ' {}'\n" 88 | + " logger.info((INDENT_FINAL ? \" \" : \"\") + \"{}\", 1);\n" 89 | + " }\n" 90 | + "}\n") 91 | .doTest(); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Find and fix misusage of SLF4J with Google Error Prone 2 | 3 | This is a plugin for [Google Error Prone](http://errorprone.info/), that detects misusage of [SLF4J](https://www.slf4j.org/). 4 | This provides almost same feature with [findbugs-slf4j](https://github.com/KengoTODA/findbugs-slf4j). 5 | 6 | [![.github/workflows/build.yml](https://github.com/KengoTODA/errorprone-slf4j/actions/workflows/build.yml/badge.svg?branch=master)](https://github.com/KengoTODA/errorprone-slf4j/actions/workflows/build.yml) 7 | [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=jp.skypencil.errorprone.slf4j%3Aerrorprone-slf4j&metric=alert_status)](https://sonarcloud.io/dashboard?id=jp.skypencil.errorprone.slf4j%3Aerrorprone-slf4j) 8 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/jp.skypencil.errorprone.slf4j/errorprone-slf4j/badge.svg)](https://maven-badges.herokuapp.com/maven-central/jp.skypencil.errorprone.slf4j/errorprone-slf4j) 9 | [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release) 10 | 11 | ## Supported Bug Patterns 12 | 13 | Current version supports following bug patterns: 14 | 15 | * [Slf4jPlaceholderMismatch](https://github.com/KengoTODA/findbugs-slf4j#slf4j_place_holder_mismatch) 16 | * [Slf4jFormatShouldBeConst](https://github.com/KengoTODA/findbugs-slf4j#slf4j_format_should_be_const) 17 | * [Slf4jLoggerShouldBePrivate](https://github.com/KengoTODA/findbugs-slf4j#slf4j_logger_should_be_private) 18 | * [Slf4jLoggerShouldBeFinal](https://github.com/KengoTODA/findbugs-slf4j#slf4j_logger_should_be_final) 19 | * [Slf4jLoggerShouldBeNonStatic](https://github.com/KengoTODA/findbugs-slf4j#slf4j_logger_should_be_non_static) 20 | * [Slf4jIllegalPassedClass](https://github.com/KengoTODA/findbugs-slf4j#slf4j_illegal_passed_class) 21 | * [Slf4jSignOnlyFormat](https://github.com/KengoTODA/findbugs-slf4j#slf4j_sign_only_format) 22 | * [Slf4jDoNotLogMessageOfExceptionExplicitly](https://github.com/KengoTODA/findbugs-slf4j#slf4j_manually_provided_message) 23 | 24 | ## Install 25 | 26 | **Requirements:** Java 17 or higher 27 | 28 | After [installation of Error Prone](https://errorprone.info/docs/installation), introduce errorprone-slf4j as plugin. Refer [official document](https://errorprone.info/docs/plugins#build-system-support) or following examples: 29 | 30 | ### Maven 31 | 32 | `maven-compiler-plugin` supports `` from version 3.5. Use it in configuration of `maven-compiler-plugin` like below: 33 | 34 | ```xml 35 | 36 | org.apache.maven.plugins 37 | maven-compiler-plugin 38 | 39 | ... 40 | 41 | 42 | jp.skypencil.errorprone.slf4j 43 | errorprone-slf4j 44 | 0.1.20 45 | 46 | 47 | 48 | 49 | ``` 50 | 51 | ### Gradle 52 | 53 | From v4.6, [Gradle supports `annotationProcessor` configuration](https://docs.gradle.org/4.6/release-notes.html#convenient-declaration-of-annotation-processor-dependencies) so you can configure your project like below: 54 | 55 | ```groovy 56 | dependencies { 57 | annotationProcessor 'jp.skypencil.errorprone.slf4j:errorprone-slf4j:0.1.20' 58 | } 59 | ``` 60 | 61 |
62 | with Kotlin DSL 63 | 64 | ```kotlin 65 | dependencies { 66 | errorprone("jp.skypencil.errorprone.slf4j:errorprone-slf4j:0.1.20") 67 | } 68 | ``` 69 | 70 | If you want to disable some rules: 71 | ```kotlin 72 | import net.ltgt.gradle.errorprone.errorprone 73 | 74 | tasks.withType().configureEach { 75 | options.errorprone { 76 | disable("Slf4jLoggerShouldBeNonStatic") 77 | } 78 | } 79 | ``` 80 | 81 |
82 | 83 | ## Copyright 84 | 85 | Copyright 2012-2022 Kengo TODA 86 | 87 | Licensed under the Apache License, Version 2.0 (the "License"); 88 | you may not use this file except in compliance with the License. 89 | You may obtain a copy of the License at 90 | 91 | http://www.apache.org/licenses/LICENSE-2.0 92 | 93 | Unless required by applicable law or agreed to in writing, software 94 | distributed under the License is distributed on an "AS IS" BASIS, 95 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 96 | See the License for the specific language governing permissions and 97 | limitations under the License. 98 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.toptal.com/developers/gitignore/api/linux,gradle,windows,eclipse,node 3 | # Edit at https://www.toptal.com/developers/gitignore?templates=linux,gradle,windows,eclipse,node 4 | 5 | ### Eclipse ### 6 | .metadata 7 | bin/ 8 | tmp/ 9 | *.tmp 10 | *.bak 11 | *.swp 12 | *~.nib 13 | local.properties 14 | .settings/ 15 | .loadpath 16 | .recommenders 17 | 18 | # External tool builders 19 | .externalToolBuilders/ 20 | 21 | # Locally stored "Eclipse launch configurations" 22 | *.launch 23 | 24 | # PyDev specific (Python IDE for Eclipse) 25 | *.pydevproject 26 | 27 | # CDT-specific (C/C++ Development Tooling) 28 | .cproject 29 | 30 | # CDT- autotools 31 | .autotools 32 | 33 | # Java annotation processor (APT) 34 | .factorypath 35 | 36 | # PDT-specific (PHP Development Tools) 37 | .buildpath 38 | 39 | # sbteclipse plugin 40 | .target 41 | 42 | # Tern plugin 43 | .tern-project 44 | 45 | # TeXlipse plugin 46 | .texlipse 47 | 48 | # STS (Spring Tool Suite) 49 | .springBeans 50 | 51 | # Code Recommenders 52 | .recommenders/ 53 | 54 | # Annotation Processing 55 | .apt_generated/ 56 | .apt_generated_test/ 57 | 58 | # Scala IDE specific (Scala & Java development for Eclipse) 59 | .cache-main 60 | .scala_dependencies 61 | .worksheet 62 | 63 | # Uncomment this line if you wish to ignore the project description file. 64 | # Typically, this file would be tracked if it contains build/dependency configurations: 65 | #.project 66 | 67 | ### Eclipse Patch ### 68 | # Spring Boot Tooling 69 | .sts4-cache/ 70 | 71 | ### Linux ### 72 | *~ 73 | 74 | # temporary files which can be created if a process still has a handle open of a deleted file 75 | .fuse_hidden* 76 | 77 | # KDE directory preferences 78 | .directory 79 | 80 | # Linux trash folder which might appear on any partition or disk 81 | .Trash-* 82 | 83 | # .nfs files are created when an open file is removed but is still being accessed 84 | .nfs* 85 | 86 | ### Node ### 87 | # Logs 88 | logs 89 | *.log 90 | npm-debug.log* 91 | yarn-debug.log* 92 | yarn-error.log* 93 | lerna-debug.log* 94 | .pnpm-debug.log* 95 | 96 | # Diagnostic reports (https://nodejs.org/api/report.html) 97 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 98 | 99 | # Runtime data 100 | pids 101 | *.pid 102 | *.seed 103 | *.pid.lock 104 | 105 | # Directory for instrumented libs generated by jscoverage/JSCover 106 | lib-cov 107 | 108 | # Coverage directory used by tools like istanbul 109 | coverage 110 | *.lcov 111 | 112 | # nyc test coverage 113 | .nyc_output 114 | 115 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 116 | .grunt 117 | 118 | # Bower dependency directory (https://bower.io/) 119 | bower_components 120 | 121 | # node-waf configuration 122 | .lock-wscript 123 | 124 | # Compiled binary addons (https://nodejs.org/api/addons.html) 125 | build/Release 126 | 127 | # Dependency directories 128 | node_modules/ 129 | jspm_packages/ 130 | 131 | # Snowpack dependency directory (https://snowpack.dev/) 132 | web_modules/ 133 | 134 | # TypeScript cache 135 | *.tsbuildinfo 136 | 137 | # Optional npm cache directory 138 | .npm 139 | 140 | # Optional eslint cache 141 | .eslintcache 142 | 143 | # Optional stylelint cache 144 | .stylelintcache 145 | 146 | # Microbundle cache 147 | .rpt2_cache/ 148 | .rts2_cache_cjs/ 149 | .rts2_cache_es/ 150 | .rts2_cache_umd/ 151 | 152 | # Optional REPL history 153 | .node_repl_history 154 | 155 | # Output of 'npm pack' 156 | *.tgz 157 | 158 | # Yarn Integrity file 159 | .yarn-integrity 160 | 161 | # dotenv environment variable files 162 | .env 163 | .env.development.local 164 | .env.test.local 165 | .env.production.local 166 | .env.local 167 | 168 | # parcel-bundler cache (https://parceljs.org/) 169 | .cache 170 | .parcel-cache 171 | 172 | # Next.js build output 173 | .next 174 | out 175 | 176 | # Nuxt.js build / generate output 177 | .nuxt 178 | dist 179 | 180 | # Gatsby files 181 | .cache/ 182 | # Comment in the public line in if your project uses Gatsby and not Next.js 183 | # https://nextjs.org/blog/next-9-1#public-directory-support 184 | # public 185 | 186 | # vuepress build output 187 | .vuepress/dist 188 | 189 | # vuepress v2.x temp and cache directory 190 | .temp 191 | 192 | # Docusaurus cache and generated files 193 | .docusaurus 194 | 195 | # Serverless directories 196 | .serverless/ 197 | 198 | # FuseBox cache 199 | .fusebox/ 200 | 201 | # DynamoDB Local files 202 | .dynamodb/ 203 | 204 | # TernJS port file 205 | .tern-port 206 | 207 | # Stores VSCode versions used for testing VSCode extensions 208 | .vscode-test 209 | 210 | # yarn v2 211 | .yarn/cache 212 | .yarn/unplugged 213 | .yarn/build-state.yml 214 | .yarn/install-state.gz 215 | .pnp.* 216 | 217 | ### Node Patch ### 218 | # Serverless Webpack directories 219 | .webpack/ 220 | 221 | # Optional stylelint cache 222 | 223 | # SvelteKit build / generate output 224 | .svelte-kit 225 | 226 | ### Windows ### 227 | # Windows thumbnail cache files 228 | Thumbs.db 229 | Thumbs.db:encryptable 230 | ehthumbs.db 231 | ehthumbs_vista.db 232 | 233 | # Dump file 234 | *.stackdump 235 | 236 | # Folder config file 237 | [Dd]esktop.ini 238 | 239 | # Recycle Bin used on file shares 240 | $RECYCLE.BIN/ 241 | 242 | # Windows Installer files 243 | *.cab 244 | *.msi 245 | *.msix 246 | *.msm 247 | *.msp 248 | 249 | # Windows shortcuts 250 | *.lnk 251 | 252 | ### Gradle ### 253 | .gradle 254 | build/ 255 | 256 | # Ignore Gradle GUI config 257 | gradle-app.setting 258 | 259 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 260 | !gradle-wrapper.jar 261 | 262 | # Cache of project 263 | .gradletasknamecache 264 | 265 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 266 | # gradle/wrapper/gradle-wrapper.properties 267 | 268 | ### Gradle Patch ### 269 | **/build/ 270 | 271 | # End of https://www.toptal.com/developers/gitignore/api/linux,gradle,windows,eclipse,node -------------------------------------------------------------------------------- /src/main/java/jp/skypencil/errorprone/slf4j/Slf4jIllegalPassedClass.java: -------------------------------------------------------------------------------- 1 | package jp.skypencil.errorprone.slf4j; 2 | 3 | import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; 4 | 5 | import com.google.auto.service.AutoService; 6 | import com.google.common.collect.ImmutableList; 7 | import com.google.errorprone.BugPattern; 8 | import com.google.errorprone.BugPattern.LinkType; 9 | import com.google.errorprone.ErrorProneVersion; 10 | import com.google.errorprone.VisitorState; 11 | import com.google.errorprone.bugpatterns.BugChecker; 12 | import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; 13 | import com.google.errorprone.fixes.SuggestedFix; 14 | import com.google.errorprone.matchers.Description; 15 | import com.google.errorprone.matchers.Matcher; 16 | import com.google.errorprone.matchers.method.MethodMatchers; 17 | import com.google.errorprone.util.ASTHelpers; 18 | import com.sun.source.tree.ClassTree; 19 | import com.sun.source.tree.ExpressionTree; 20 | import com.sun.source.tree.MethodInvocationTree; 21 | import com.sun.source.tree.VariableTree; 22 | import com.sun.source.util.TreeScanner; 23 | import com.sun.tools.javac.code.Symbol.ClassSymbol; 24 | import com.sun.tools.javac.code.Symbol.TypeSymbol; 25 | import com.sun.tools.javac.code.Type; 26 | import com.sun.tools.javac.code.Type.ClassType; 27 | import java.util.ArrayList; 28 | import java.util.List; 29 | import java.util.stream.Collectors; 30 | import javax.lang.model.element.Modifier; 31 | 32 | @BugPattern( 33 | altNames = {"IllegalPassedClass"}, 34 | summary = "LoggerFactory.getLogger(Class) should get the class that defines variable", 35 | tags = {"SLF4J"}, 36 | link = "https://github.com/KengoTODA/findbugs-slf4j#slf4j_illegal_passed_class", 37 | linkType = LinkType.CUSTOM, 38 | severity = WARNING) 39 | @AutoService(BugChecker.class) 40 | public class Slf4jIllegalPassedClass extends BugChecker implements MethodInvocationTreeMatcher { 41 | 42 | private static final long serialVersionUID = 8309704818374164342L; 43 | 44 | @Override 45 | public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { 46 | TypeSymbol type = tree.accept(new LoggerInitializerVisitor(), state); 47 | if (type == null) { 48 | return Description.NO_MATCH; 49 | } 50 | 51 | ImmutableList enclosingClasses = listEnclosingClasses(state); 52 | for (ClassSymbol enclosingSymbol : enclosingClasses) { 53 | if (ASTHelpers.isSameType(type.type, enclosingSymbol.type, state)) { 54 | return Description.NO_MATCH; 55 | } 56 | } 57 | 58 | String message = 59 | String.format( 60 | "LoggerFactory.getLogger(Class) should get one of [%s] but it gets %s", 61 | enclosingClasses.stream().map(ClassSymbol::className).collect(Collectors.joining(",")), 62 | type.getSimpleName()); 63 | Description.Builder builder = buildDescription(tree).setMessage(message); 64 | 65 | VariableTree variableTree = state.findEnclosing(VariableTree.class); 66 | if (variableTree != null && !variableTree.getModifiers().getFlags().contains(Modifier.STATIC)) { 67 | builder.addFix( 68 | SuggestedFix.builder().replace(tree.getArguments().get(0), "getClass()").build()); 69 | } 70 | for (ClassSymbol enclosingSymbol : enclosingClasses) { 71 | builder.addFix( 72 | SuggestedFix.builder() 73 | .replace(tree.getArguments().get(0), enclosingSymbol.getSimpleName() + ".class") 74 | .build()); 75 | } 76 | return builder.build(); 77 | } 78 | 79 | private static ImmutableList listEnclosingClasses(VisitorState state) { 80 | ClassTree enclosing = state.findEnclosing(ClassTree.class); 81 | if (enclosing == null) { 82 | return ImmutableList.of(); 83 | } 84 | 85 | List result = new ArrayList<>(); 86 | ClassSymbol enclosingSymbol = ASTHelpers.getSymbol(enclosing); 87 | while (enclosingSymbol != null) { 88 | result.add(enclosingSymbol); 89 | enclosingSymbol = ASTHelpers.enclosingClass(enclosingSymbol); 90 | } 91 | return ImmutableList.copyOf(result); 92 | } 93 | 94 | private static final class LoggerInitializerVisitor 95 | extends TreeScanner { 96 | @Override 97 | public TypeSymbol visitMethodInvocation(MethodInvocationTree node, VisitorState state) { 98 | if (!MatherHolder.isGetLogger.matches(node, state)) { 99 | return null; 100 | } 101 | 102 | ExpressionTree arg = node.getArguments().get(0); 103 | ClassType type = (ClassType) ASTHelpers.getType(arg); 104 | Type typeParameter = type.getTypeArguments().get(0); 105 | return typeParameter.asElement(); 106 | } 107 | } 108 | 109 | /** 110 | * Apply the initialization-on-demand holder idiom to check the version of Errorprone only when we 111 | * use the matcher which depends on new API definition from {@code 2.11.0}. 112 | * 113 | * @see GitHub Issue about the API 114 | * change on the Errorprone side 115 | * @see Initialization-on-demand 117 | * holder idiom (Wikipedia) 118 | */ 119 | static final class MatherHolder { 120 | static { 121 | boolean supported = 122 | ErrorProneVersion.loadVersionFromPom() 123 | .transform(MatherHolder::checkSupportedVersion) 124 | .or(true); 125 | if (!supported) { 126 | throw new IllegalStateException("Run this rule with Errorprone 2.11.0 or later."); 127 | } 128 | } 129 | 130 | static boolean checkSupportedVersion(String version) { 131 | String[] split = version.split("\\.", 3); 132 | int major = Integer.parseInt(split[0], 10); 133 | if (major > 2) { 134 | // assuming this version uses new API definition 135 | return true; 136 | } 137 | int minor = Integer.parseInt(split[1], 10); 138 | return minor >= 11; 139 | } 140 | 141 | static Matcher isGetLogger = 142 | MethodMatchers.staticMethod() 143 | .onClass("org.slf4j.LoggerFactory") 144 | .named("getLogger") 145 | .withParameters("java.lang.Class"); 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /src/test/java/jp/skypencil/errorprone/slf4j/Slf4jPlaceholderMismatchTest.java: -------------------------------------------------------------------------------- 1 | package jp.skypencil.errorprone.slf4j; 2 | 3 | import com.google.errorprone.CompilationTestHelper; 4 | import org.junit.Before; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.junit.runners.JUnit4; 8 | 9 | @RunWith(JUnit4.class) 10 | public class Slf4jPlaceholderMismatchTest { 11 | private CompilationTestHelper helper; 12 | 13 | @Before 14 | public void setup() { 15 | helper = CompilationTestHelper.newInstance(Slf4jPlaceholderMismatch.class, getClass()); 16 | } 17 | 18 | @Test 19 | public void testNonConstantFormat() { 20 | helper 21 | .addSourceLines( 22 | "NonConstantFormat.java", 23 | "import org.slf4j.Logger;\n" 24 | + "import org.slf4j.LoggerFactory;\n" 25 | + "\n" 26 | + "public class NonConstantFormat {\n" 27 | + " private final Logger logger = LoggerFactory.getLogger(getClass());\n" 28 | + " void method() {\n" 29 | + " logger.info(this + \"{}\");" 30 | + " }\n" 31 | + "}") 32 | .expectNoDiagnostics() 33 | .doTest(); 34 | } 35 | 36 | @Test 37 | public void testMarker() { 38 | CompilationTestHelper helper = 39 | CompilationTestHelper.newInstance(Slf4jPlaceholderMismatch.class, getClass()); 40 | helper 41 | .addSourceLines( 42 | "WithMarker.java", 43 | "import org.slf4j.Logger;\n" 44 | + "import org.slf4j.LoggerFactory;\n" 45 | + "import org.slf4j.MarkerFactory;\n" 46 | + "import org.slf4j.Marker;\n" 47 | + "\n" 48 | + "public class WithMarker {\n" 49 | + " private final Logger logger = LoggerFactory.getLogger(getClass());\n" 50 | + " private final Marker marker = MarkerFactory.getMarker(\"Sample\");\n" 51 | + " void method() {\n" 52 | + " logger.info(marker, \"I have one placeholder, one parameter and one marker instance. {}\", 1);" 53 | + " }\n" 54 | + "}") 55 | .expectNoDiagnostics() 56 | .doTest(); 57 | } 58 | 59 | @Test 60 | public void testThrowable() { 61 | CompilationTestHelper helper = 62 | CompilationTestHelper.newInstance(Slf4jPlaceholderMismatch.class, getClass()); 63 | helper 64 | .addSourceLines( 65 | "WithThrowable.java", 66 | "import org.slf4j.Logger;\n" 67 | + "import org.slf4j.LoggerFactory;\n" 68 | + "\n" 69 | + "public class WithThrowable {\n" 70 | + " private final Logger logger = LoggerFactory.getLogger(getClass());\n" 71 | + " void method() {\n" 72 | + " logger.info(\"I have one placeholder, one parameter and one throwable instance. {}\", 1, new Exception());" 73 | + " }\n" 74 | + "}") 75 | .expectNoDiagnostics() 76 | .doTest(); 77 | } 78 | 79 | @Test 80 | public void testTooManyPlaceholders() { 81 | CompilationTestHelper helper = 82 | CompilationTestHelper.newInstance(Slf4jPlaceholderMismatch.class, getClass()); 83 | helper 84 | .addSourceLines( 85 | "TooManyPlaceholders.java", 86 | "import org.slf4j.Logger;\n" 87 | + "import org.slf4j.LoggerFactory;\n" 88 | + "\n" 89 | + "public class TooManyPlaceholders {\n" 90 | + " private final Logger logger = LoggerFactory.getLogger(getClass());\n" 91 | + " void method() {\n" 92 | + " // BUG: Diagnostic contains: Count of placeholder (2) does not match with count of parameter (1)\n" 93 | + " logger.info(\"I have two placeholders and one parameter! {} {}\", 1);" 94 | + " }\n" 95 | + "}") 96 | .doTest(); 97 | } 98 | 99 | @Test 100 | public void testTooManyParams() { 101 | CompilationTestHelper helper = 102 | CompilationTestHelper.newInstance(Slf4jPlaceholderMismatch.class, getClass()); 103 | helper 104 | .addSourceLines( 105 | "TooManyParams.java", 106 | "import org.slf4j.Logger;\n" 107 | + "import org.slf4j.LoggerFactory;\n" 108 | + "\n" 109 | + "public class TooManyParams {\n" 110 | + " private final Logger logger = LoggerFactory.getLogger(getClass());\n" 111 | + " void method() {\n" 112 | + " // BUG: Diagnostic contains: Count of placeholder (1) does not match with count of parameter (2)\n" 113 | + " logger.info(\"I have one placeholder and two parameters! {}\", 1, 2);" 114 | + " }\n" 115 | + "}") 116 | .doTest(); 117 | } 118 | 119 | @Test 120 | public void testVarArg() { 121 | CompilationTestHelper helper = 122 | CompilationTestHelper.newInstance(Slf4jPlaceholderMismatch.class, getClass()); 123 | helper 124 | .addSourceLines( 125 | "VarArg.java", 126 | "import org.slf4j.Logger;\n" 127 | + "import org.slf4j.LoggerFactory;\n" 128 | + "\n" 129 | + "public class VarArg {\n" 130 | + " private final Logger logger = LoggerFactory.getLogger(getClass());\n" 131 | + " void method() {\n" 132 | + " logger.info(\"I have four placeholders and parameters! {}, {}, {}, {}\", 1, 2, 3, 4);" 133 | + " }\n" 134 | + "}") 135 | .expectNoDiagnostics() 136 | .doTest(); 137 | } 138 | 139 | @Test 140 | public void testVarArgWithException() { 141 | CompilationTestHelper helper = 142 | CompilationTestHelper.newInstance(Slf4jPlaceholderMismatch.class, getClass()); 143 | helper 144 | .addSourceLines( 145 | "VarArg.java", 146 | "import org.slf4j.Logger;\n" 147 | + "import org.slf4j.LoggerFactory;\n" 148 | + "\n" 149 | + "public class VarArg {\n" 150 | + " private final Logger logger = LoggerFactory.getLogger(getClass());\n" 151 | + " void method() {\n" 152 | + " logger.info(\"I have four placeholders and parameters! {}, {}, {}, {}\", 1, 2, 3, 4, new Error());" 153 | + " }\n" 154 | + "}") 155 | .expectNoDiagnostics() 156 | .doTest(); 157 | } 158 | 159 | @Test 160 | public void testNoParams() { 161 | CompilationTestHelper helper = 162 | CompilationTestHelper.newInstance(Slf4jPlaceholderMismatch.class, getClass()); 163 | helper 164 | .addSourceLines( 165 | "NoParam.java", 166 | "import org.slf4j.Logger;\n" 167 | + "import org.slf4j.LoggerFactory;\n" 168 | + "\n" 169 | + "public class NoParam {\n" 170 | + " private final Logger logger = LoggerFactory.getLogger(getClass());\n" 171 | + " void method() {\n" 172 | + " // BUG: Diagnostic contains: Count of placeholder (1) does not match with count of parameter (0)\n" 173 | + " logger.info(\"I have one placeholder and no parameter! {}\");" 174 | + " }\n" 175 | + "}") 176 | .doTest(); 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH="\\\"\\\"" 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | if ! command -v java >/dev/null 2>&1 137 | then 138 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 139 | 140 | Please set the JAVA_HOME variable in your environment to match the 141 | location of your Java installation." 142 | fi 143 | fi 144 | 145 | # Increase the maximum file descriptors if we can. 146 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 147 | case $MAX_FD in #( 148 | max*) 149 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 150 | # shellcheck disable=SC2039,SC3045 151 | MAX_FD=$( ulimit -H -n ) || 152 | warn "Could not query maximum file descriptor limit" 153 | esac 154 | case $MAX_FD in #( 155 | '' | soft) :;; #( 156 | *) 157 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 158 | # shellcheck disable=SC2039,SC3045 159 | ulimit -n "$MAX_FD" || 160 | warn "Could not set maximum file descriptor limit to $MAX_FD" 161 | esac 162 | fi 163 | 164 | # Collect all arguments for the java command, stacking in reverse order: 165 | # * args from the command line 166 | # * the main class name 167 | # * -classpath 168 | # * -D...appname settings 169 | # * --module-path (only if needed) 170 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 171 | 172 | # For Cygwin or MSYS, switch paths to Windows format before running java 173 | if "$cygwin" || "$msys" ; then 174 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 175 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 176 | 177 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 178 | 179 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 180 | for arg do 181 | if 182 | case $arg in #( 183 | -*) false ;; # don't mess with options #( 184 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 185 | [ -e "$t" ] ;; #( 186 | *) false ;; 187 | esac 188 | then 189 | arg=$( cygpath --path --ignore --mixed "$arg" ) 190 | fi 191 | # Roll the args list around exactly as many times as the number of 192 | # args, so each arg winds up back in the position where it started, but 193 | # possibly modified. 194 | # 195 | # NB: a `for` loop captures its iteration list before it begins, so 196 | # changing the positional parameters here affects neither the number of 197 | # iterations, nor the values presented in `arg`. 198 | shift # remove old arg 199 | set -- "$@" "$arg" # push replacement arg 200 | done 201 | fi 202 | 203 | 204 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 205 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 206 | 207 | # Collect all arguments for the java command: 208 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 209 | # and any embedded shellness will be escaped. 210 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 211 | # treated as '${Hostname}' itself on the command line. 212 | 213 | set -- \ 214 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 215 | -classpath "$CLASSPATH" \ 216 | -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ 217 | "$@" 218 | 219 | # Stop when "xargs" is not available. 220 | if ! command -v xargs >/dev/null 2>&1 221 | then 222 | die "xargs is not available" 223 | fi 224 | 225 | # Use "xargs" to parse quoted args. 226 | # 227 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 228 | # 229 | # In Bash we could simply go: 230 | # 231 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 232 | # set -- "${ARGS[@]}" "$@" 233 | # 234 | # but POSIX shell has neither arrays nor command substitution, so instead we 235 | # post-process each arg (as a line of input to sed) to backslash-escape any 236 | # character that might be a shell metacharacter, then use eval to reverse 237 | # that process (while maintaining the separation between arguments), and wrap 238 | # the whole thing up as a single "set" statement. 239 | # 240 | # This will of course break if any of these variables contains a newline or 241 | # an unmatched quote. 242 | # 243 | 244 | eval "set -- $( 245 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 246 | xargs -n1 | 247 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 248 | tr '\n' ' ' 249 | )" '"$@"' 250 | 251 | exec "$JAVACMD" "$@" 252 | -------------------------------------------------------------------------------- /src/test/java/jp/skypencil/errorprone/slf4j/Slf4jIllegalPassedClassTest.java: -------------------------------------------------------------------------------- 1 | package jp.skypencil.errorprone.slf4j; 2 | 3 | import static org.junit.Assert.assertFalse; 4 | import static org.junit.Assert.assertTrue; 5 | 6 | import com.google.errorprone.BugCheckerRefactoringTestHelper; 7 | import com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers; 8 | import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode; 9 | import com.google.errorprone.CompilationTestHelper; 10 | import com.google.errorprone.bugpatterns.BugChecker; 11 | import java.io.IOException; 12 | import org.junit.Test; 13 | 14 | public class Slf4jIllegalPassedClassTest { 15 | @Test 16 | public void testSupportedVersion() { 17 | assertTrue(Slf4jIllegalPassedClass.MatherHolder.checkSupportedVersion("3.0.0")); 18 | assertTrue(Slf4jIllegalPassedClass.MatherHolder.checkSupportedVersion("2.11.0")); 19 | assertFalse(Slf4jIllegalPassedClass.MatherHolder.checkSupportedVersion("2.10.0")); 20 | } 21 | 22 | @Test 23 | public void testRefactoringInstanceField() throws IOException { 24 | BugChecker checker = new Slf4jIllegalPassedClass(); 25 | BugCheckerRefactoringTestHelper helper = 26 | BugCheckerRefactoringTestHelper.newInstance(checker, getClass()); 27 | helper 28 | .addInputLines( 29 | "PrivateLogger.java", 30 | "import org.slf4j.Logger;\n" 31 | + "import org.slf4j.LoggerFactory;\n" 32 | + "\n" 33 | + "public class PrivateLogger {\n" 34 | + " private final Logger logger = LoggerFactory.getLogger(String.class);\n" 35 | + "}") 36 | .addOutputLines( 37 | "PrivateLogger.java", 38 | "import org.slf4j.Logger;\n" 39 | + "import org.slf4j.LoggerFactory;\n" 40 | + "\n" 41 | + "public class PrivateLogger {\n" 42 | + " private final Logger logger = LoggerFactory.getLogger(getClass());\n" 43 | + "}\n" 44 | + "") 45 | .doTest(TestMode.TEXT_MATCH); 46 | } 47 | 48 | @Test 49 | public void testRefactoringStaticField() throws IOException { 50 | BugChecker checker = new Slf4jIllegalPassedClass(); 51 | BugCheckerRefactoringTestHelper helper = 52 | BugCheckerRefactoringTestHelper.newInstance(checker, getClass()); 53 | helper 54 | .addInputLines( 55 | "PrivateLogger.java", 56 | "import org.slf4j.Logger;\n" 57 | + "import org.slf4j.LoggerFactory;\n" 58 | + "\n" 59 | + "public class PrivateLogger {\n" 60 | + " private static final Logger LOGGER = LoggerFactory.getLogger(String.class);\n" 61 | + "}") 62 | .addOutputLines( 63 | "PrivateLogger.java", 64 | "import org.slf4j.Logger;\n" 65 | + "import org.slf4j.LoggerFactory;\n" 66 | + "\n" 67 | + "public class PrivateLogger {\n" 68 | + " private static final Logger LOGGER = LoggerFactory.getLogger(PrivateLogger.class);\n" 69 | + "}\n" 70 | + "") 71 | .doTest(TestMode.TEXT_MATCH); 72 | } 73 | 74 | @Test 75 | public void test2ndFixForInstanceField() throws IOException { 76 | BugChecker checker = new Slf4jIllegalPassedClass(); 77 | BugCheckerRefactoringTestHelper helper = 78 | BugCheckerRefactoringTestHelper.newInstance(checker, getClass()) 79 | .setFixChooser(FixChoosers.SECOND); 80 | helper 81 | .addInputLines( 82 | "PrivateLogger.java", 83 | "import org.slf4j.Logger;\n" 84 | + "import org.slf4j.LoggerFactory;\n" 85 | + "\n" 86 | + "public class PrivateLogger {\n" 87 | + " private final Logger logger = LoggerFactory.getLogger(String.class);\n" 88 | + "}") 89 | .addOutputLines( 90 | "PrivateLogger.java", 91 | "import org.slf4j.Logger;\n" 92 | + "import org.slf4j.LoggerFactory;\n" 93 | + "\n" 94 | + "public class PrivateLogger {\n" 95 | + " private final Logger logger = LoggerFactory.getLogger(PrivateLogger.class);\n" 96 | + "}\n" 97 | + "") 98 | .doTest(TestMode.TEXT_MATCH); 99 | } 100 | 101 | @Test 102 | public void testRefactoringInnerClass() throws IOException { 103 | BugChecker checker = new Slf4jIllegalPassedClass(); 104 | BugCheckerRefactoringTestHelper helper = 105 | BugCheckerRefactoringTestHelper.newInstance(checker, getClass()) 106 | .setFixChooser(FixChoosers.SECOND); 107 | helper 108 | .addInputLines( 109 | "PrivateLogger.java", 110 | "import org.slf4j.Logger;\n" 111 | + "import org.slf4j.LoggerFactory;\n" 112 | + "\n" 113 | + "public class PrivateLogger {\n" 114 | + " private static class InnerClass {\n" 115 | + " private static final Logger LOGGER = LoggerFactory.getLogger(String.class);\n" 116 | + " }\n" 117 | + "}") 118 | .addOutputLines( 119 | "PrivateLogger.java", 120 | "import org.slf4j.Logger;\n" 121 | + "import org.slf4j.LoggerFactory;\n" 122 | + "\n" 123 | + "public class PrivateLogger {\n" 124 | + " private static class InnerClass {\n" 125 | + " private static final Logger LOGGER = LoggerFactory.getLogger(PrivateLogger.class);\n" 126 | + " }\n" 127 | + "}\n" 128 | + "") 129 | .doTest(TestMode.TEXT_MATCH); 130 | } 131 | 132 | @Test 133 | public void testRefactoringInnerClass2() throws IOException { 134 | BugChecker checker = new Slf4jIllegalPassedClass(); 135 | BugCheckerRefactoringTestHelper helper = 136 | BugCheckerRefactoringTestHelper.newInstance(checker, getClass()) 137 | .setFixChooser(FixChoosers.FIRST); 138 | helper 139 | .addInputLines( 140 | "PrivateLogger.java", 141 | "import org.slf4j.Logger;\n" 142 | + "import org.slf4j.LoggerFactory;\n" 143 | + "\n" 144 | + "public class PrivateLogger {\n" 145 | + " private static class InnerClass {\n" 146 | + " private static final Logger LOGGER = LoggerFactory.getLogger(String.class);\n" 147 | + " }\n" 148 | + "}") 149 | .addOutputLines( 150 | "PrivateLogger.java", 151 | "import org.slf4j.Logger;\n" 152 | + "import org.slf4j.LoggerFactory;\n" 153 | + "\n" 154 | + "public class PrivateLogger {\n" 155 | + " private static class InnerClass {\n" 156 | + " private static final Logger LOGGER = LoggerFactory.getLogger(InnerClass.class);\n" 157 | + " }\n" 158 | + "}\n" 159 | + "") 160 | .doTest(TestMode.TEXT_MATCH); 161 | } 162 | 163 | @Test 164 | public void testOtherField() throws IOException { 165 | CompilationTestHelper helper = 166 | CompilationTestHelper.newInstance(Slf4jIllegalPassedClass.class, getClass()); 167 | helper 168 | .addSourceLines( 169 | "WithLoggerFactory.java", 170 | "import org.slf4j.Logger;\n" 171 | + "import org.slf4j.ILoggerFactory;\n" 172 | + "import org.slf4j.LoggerFactory;\n" 173 | + "\n" 174 | + "public class WithLoggerFactory {\n" 175 | + " private final String HELLO = \"World\";" 176 | + " private final ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();\n" 177 | + " private final Logger logger = LoggerFactory.getLogger(\"string\");\n" 178 | + "}") 179 | .expectNoDiagnostics() 180 | .doTest(); 181 | } 182 | 183 | @Test 184 | public void testClassWithoutProblem() throws IOException { 185 | CompilationTestHelper helper = 186 | CompilationTestHelper.newInstance(Slf4jIllegalPassedClass.class, getClass()); 187 | helper 188 | .addSourceLines( 189 | "PrivateLogger.java", 190 | "import org.slf4j.Logger;\n" 191 | + "import org.slf4j.LoggerFactory;\n" 192 | + "\n" 193 | + "public class PrivateLogger {\n" 194 | + " private final Logger logger = LoggerFactory.getLogger(PrivateLogger.class);\n" 195 | + "}") 196 | .expectNoDiagnostics() 197 | .doTest(); 198 | } 199 | 200 | @Test 201 | public void testInnerClassWithoutProblem() throws IOException { 202 | CompilationTestHelper helper = 203 | CompilationTestHelper.newInstance(Slf4jIllegalPassedClass.class, getClass()); 204 | helper 205 | .addSourceLines( 206 | "PrivateLogger.java", 207 | "import org.slf4j.Logger;\n" 208 | + "import org.slf4j.LoggerFactory;\n" 209 | + "\n" 210 | + "public class PrivateLogger {\n" 211 | + " private static class InnerClass {\n" 212 | + " private static final Logger LOGGER = LoggerFactory.getLogger(InnerClass.class);\n" 213 | + " private final Logger logger = LoggerFactory.getLogger(PrivateLogger.class);\n" 214 | + " }\n" 215 | + "}") 216 | .expectNoDiagnostics() 217 | .doTest(); 218 | } 219 | 220 | @Test 221 | public void testMethodParameter() throws IOException { 222 | CompilationTestHelper helper = 223 | CompilationTestHelper.newInstance(Slf4jIllegalPassedClass.class, getClass()); 224 | helper 225 | .addSourceLines( 226 | "PrivateLogger.java", 227 | "import org.slf4j.Logger;\n" 228 | + "import org.slf4j.LoggerFactory;\n" 229 | + "\n" 230 | + "public class PrivateLogger {\n" 231 | + " private void method (String string) {\n" 232 | + " }\n" 233 | + "}") 234 | .expectNoDiagnostics() 235 | .doTest(); 236 | } 237 | } 238 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------