Reputation: 1016
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"
}
}
Upvotes: 8
Views: 8041
Reputation: 3109
Turning Danny Lagrouw's comment into an answer:
You can get a similar to @Slf4j
low-boilerplate solution that does not require you to specify the class manually by using Micro Utils' kotlin-logging
import mu.KotlinLogging
private val log = KotlinLogging.logger {}
class LoggingDemoClass() {
fun logSometing() {
log.info("Logging like a pro!")
}
}
Caveat: I've only just started using it but and haven't investigated any of the kotlin sugar it puts on top of Slf4j but so far it seems to handle well enough as a drop-in replacement for @Slf4j
in kotlin code.
Upvotes: 1
Reputation: 81
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
Upvotes: 7