Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement PreferStaticLoggers error-prone check #1446

Merged
merged 3 commits into from
Jul 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@ Safe Logging can be found at [github.com/palantir/safe-logging](https://github.c
- `ExtendsErrorOrThrowable`: Avoid extending Error (or subclasses of it) or Throwable directly.
- `ImmutablesStyleCollision`: Prevent unintentionally voiding immutables Style meta-annotations through the introduction of inline style annotations.
- `TooManyArguments`: Prefer Interface that take few arguments rather than many.
- `PreferStaticLoggers`: Prefer static loggers over instance loggers.

### Programmatic Application

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.palantir.baseline.errorprone;

import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.matchers.method.MethodMatchers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import javax.lang.model.element.Modifier;

@AutoService(BugChecker.class)
@BugPattern(
name = "PreferStaticLoggers",
link = "https://github.com/palantir/gradle-baseline#baseline-error-prone-checks",
linkType = BugPattern.LinkType.CUSTOM,
providesFix = BugPattern.ProvidesFix.REQUIRES_HUMAN_ATTENTION,
severity = SeverityLevel.WARNING,
summary = "Prefer static logger instances over instances to reduce object initialization costs and heap "
+ "overhead. Some logger frameworks may run expensive classloader lookups when loggers are requested "
+ "based on configuration.")
public final class PreferStaticLoggers extends BugChecker implements BugChecker.VariableTreeMatcher {

private static final Matcher<Tree> IS_LOGGER = Matchers.isSubtypeOf("org.slf4j.Logger");
private static final Matcher<ExpressionTree> LOGGER_FACTORY = MethodMatchers.staticMethod()
.onClass("org.slf4j.LoggerFactory")
.named("getLogger")
.withParameters("java.lang.Class");

private static final Matcher<ExpressionTree> GET_CLASS =
MethodMatchers.instanceMethod().anyClass().named("getClass").withParameters();

private static final Matcher<VariableTree> IS_FIELD = Matchers.isField();

@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
// Only applies to loggers with initializers, to avoid impacting
// classes which may take a logger as an argument.
ExpressionTree initializer = tree.getInitializer();
if (initializer == null) {
return Description.NO_MATCH;
}
if (!IS_FIELD.matches(tree, state)) {
return Description.NO_MATCH;
}
if (!IS_LOGGER.matches(tree.getType(), state)) {
return Description.NO_MATCH;
}
VarSymbol symbol = ASTHelpers.getSymbol(tree);
if (symbol.isStatic()) {
return Description.NO_MATCH;
}
SuggestedFix.Builder fix = SuggestedFix.builder();
SuggestedFixes.addModifiers(tree, state, Modifier.STATIC).ifPresent(fix::merge);
if (LOGGER_FACTORY.matches(initializer, state)) {
MethodInvocationTree invocation = (MethodInvocationTree) initializer;
ExpressionTree argument = invocation.getArguments().get(0);
if (ASTHelpers.getReceiver(argument) == null && GET_CLASS.matches(argument, state)) {
fix.replace(
argument, SuggestedFixes.qualifyType(state, fix, ASTHelpers.enclosingClass(symbol) + ".class"));
}
}
return buildDescription(tree).addFix(fix.build()).build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* (c) Copyright 2020 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.palantir.baseline.errorprone;

import org.junit.jupiter.api.Test;

class PreferStaticLoggersTest {

@Test
void testNonstaticLogger_stringName() {
fix().addInputLines(
"Test.java",
"import org.slf4j.*;",
"class Test {",
" private final Logger log = LoggerFactory.getLogger(\"foo\");",
"}")
.addOutputLines(
"Test.java",
"import org.slf4j.*;",
"class Test {",
" private static final Logger log = LoggerFactory.getLogger(\"foo\");",
"}")
.doTest();
}

@Test
void testNonstaticLogger_getClassName() {
fix().addInputLines(
"Test.java",
"import org.slf4j.*;",
"class Test {",
" private final Logger log = LoggerFactory.getLogger(getClass());",
"}")
.addOutputLines(
"Test.java",
"import org.slf4j.*;",
"class Test {",
" private static final Logger log = LoggerFactory.getLogger(Test.class);",
"}")
.doTest();
}

RefactoringValidator fix() {
return RefactoringValidator.of(new PreferStaticLoggers(), getClass());
}
}
5 changes: 5 additions & 0 deletions changelog/@unreleased/pr-1446.v2.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
type: improvement
improvement:
description: Implement PreferStaticLoggers error-prone check
links:
- https://github.com/palantir/gradle-baseline/pull/1446
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public class BaselineErrorProneExtension {
"PreferListsPartition",
"PreferSafeLoggableExceptions",
"PreferSafeLoggingPreconditions",
"PreferStaticLoggers",
"PublicConstructorForAbstractClass",
"ReadReturnValueIgnored",
"RedundantMethodReference",
Expand Down