Slf4j注释如何将类字段日志添加到给定的类?

时间:2019-01-24 07:13:48

标签: java logging annotations log4j2 slf4j

这是我的groovy文件,我没有在其中声明log变量,但是在添加@ Slf4j批注时会推断出log变量的类型。

@Slf4j
class MyGroovySampleAnnotationLogTest {
    public void logTest() {
        log.info("To Test Log info");
    }

    public static void main(String[] args) {
        MyGroovySampleAnnotationLogTest mySampleAnnotationLogTest = new MyGroovySampleAnnotationLogTest();
        mySampleAnnotationLogTest.logTest();
    }

}

我用与Slf4j相同的代码创建了一个自定义批注,并引用了该批注,但是当我将其更改为@ MySlf4j时,IDE无法绑定该变量。谁能让我知道@ Slf4j如何将类级别的“ log”变量注入MyGroovySampleAnnotationLogTest?为什么@ MySlf4j注释不起作用?

@java.lang.annotation.Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@GroovyASTTransformationClass("org.codehaus.groovy.transform.LogASTTransformation")
public @interface MySlf4j {
    String value() default "log";
    String category() default LogASTTransformation.DEFAULT_CATEGORY_NAME;
    Class<? extends LogASTTransformation.LoggingStrategy> loggingStrategy() default groovy.util.logging.Slf4j.Slf4jLoggingStrategy.class;

    public static class Slf4jLoggingStrategy extends LogASTTransformation.AbstractLoggingStrategy {
        private static final String LOGGER_NAME = "org.slf4j.Logger";
        private static final String FACTORY_NAME = "org.slf4j.LoggerFactory";

        protected Slf4jLoggingStrategy(final GroovyClassLoader loader) {
            super(loader);
        }

        public FieldNode addLoggerFieldToClass(ClassNode classNode, String logFieldName, String categoryName) {
            return classNode.addField(logFieldName,
                    MyOpcodes.ACC_FINAL | MyOpcodes.ACC_TRANSIENT | MyOpcodes.ACC_STATIC | MyOpcodes.ACC_PRIVATE,
                    classNode(LOGGER_NAME),
                    new MethodCallExpression(
                            new ClassExpression(classNode(FACTORY_NAME)),
                            "getLogger",
                            new ConstantExpression(getCategoryName(classNode, categoryName))));
        }

        public boolean isLoggingMethod(String methodName) {
            return methodName.matches("error|warn|info|debug|trace");
        }

        public Expression wrapLoggingMethodCall(Expression logVariable, String methodName, Expression originalExpression) {
            MethodCallExpression condition = new MethodCallExpression(
                    logVariable,
                    "is" + methodName.substring(0, 1).toUpperCase(Locale.ENGLISH) + methodName.substring(1, methodName.length()) + "Enabled",
                    ArgumentListExpression.EMPTY_ARGUMENTS);
            condition.setImplicitThis(false);

            return new TernaryExpression(
                    new BooleanExpression(condition),
                    originalExpression,
                    ConstantExpression.NULL);
        }
    }

}

0 个答案:

没有答案