【问题标题】:Implement @slf4j annotation from Lombok in Kotlin在 Kotlin 中实现来自 Lombok 的 @slf4j 注解
【发布时间】:2020-06-10 16:01:13
【问题描述】:

有没有办法在 Kotlin 中用注解类实现类似于 Lombok 的注解 @slf4j 的东西?

现在我有一个为我实例化 Logger Factory 的扩展函数,我必须在每个类中创建这些变量,就像下面的示例一样:

@RestController
@RequestMapping("/api/v1/sample")
class SampleController() {
    private val log = logger()

    @GetMapping
    fun show(): String {
        log.info("SOME LOGGING MESSAGE")
        return "OK"
    }
}

inline fun <reified T> T.logger(): Logger {
    if (T::class.isCompanion) {
        return LoggerFactory.getLogger(T::class.java.enclosingClass)
    }
    return LoggerFactory.getLogger(T::class.java)
}

我想要实现的是:

@Logger
@RestController
@RequestMapping("/api/v1/sample")
class SampleController() {
    @GetMapping
    fun show(): String {
        log.info("SOME LOGGING MESSAGE")
        return "OK"
    }
}

【问题讨论】:

  • 必须是注解吗?我们使用 Kotlin Logging (github.com/MicroUtils/kotlin-logging),它允许在类定义的正上方放置一个静态字段:private val logger = KotlinLogging.logger {} 然后您可以根据需要在您的类中使用此记录器。

标签: kotlin annotations


【解决方案1】:

昨天做了这个漂亮的东西

@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class Log {
    companion object {
        inline var <reified T> T.log: Logger
            get() = LoggerFactory.getLogger(T::class.java)
            set(value) {}
    }
}
编辑:

不要使用上面的这个烂摊子。使用

companion object {
    private val log: Logger = LoggerFactory.getLogger(this::class.java)
}

Idiomatic way of logging in Kotlin

【讨论】:

  • 第一个不行是什么原因?
  • @FrancisFredrickValero 它可以正常工作,但允许 AnyType.log() 这样它造成的混乱并不能弥补它的可访问性。任何类也都可以访问这个方法,所以注解部分是多余的
猜你喜欢
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-08
  • 1970-01-01
  • 2020-07-18
  • 2021-01-31
相关资源
最近更新 更多