Implement @slf4j annotation from Lombok in Kotlin

Viewed 2952

Is there a way to implement something similar to Lombok's annotation @slf4j with annotation class in Kotlin?

Right now I have an extension function that instantiates a Logger Factory for me, and I must create these variables in each of my classes just like the example below:

@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)
}

What I want to achieve is something like:

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

made this pretty thing yesterday

@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) {}
    }
}
edit:

Don't use this mess above. use

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

see Idiomatic way of logging in Kotlin

Related