Is there a more generic way to do ```LoggerFactory...
# getting-started
k
Is there a more generic way to do
Copy code
LoggerFactory.getLogger(SomeService::class.java)
in Kotlin where I won't need to specify the exact class?
c
It depends on your logging library. KotlinLogging uses an empty function with a lambda to steal the class information (
val logger = KotlinLogging.logger {}
), my Pedestal library lets you pass an object directly (
val logger = loggerFor(this)
)
c
k
Typical sl4j with logback project
a
there are a lot of suggestions here https://www.baeldung.com/kotlin/logging What you probably want is 6.4, a util method with a reified type parameter, or 7, using a delegate. But do consider using kotlin-logging because it includes these fixes and some other Kotlin-friendly helpers. Under the hood it’d still be slf4j + logback.
For fun, here’s a logger delegate that doesn’t fetch the logger every time. It uses a delegate provider to initialise the delegate with a logger, so the logger can be re-used. https://pl.kotl.in/xrSCvWlQs (I used Java Logging so it could run in Kotlin playground)
k
Thanks for the suggestions, I will take a closer look at kotlin-logging.
e
after https://youtrack.jetbrains.com/issue/KT-11968/Research-and-prototype-namespace-based-solution-for-statics-and-static-extensions, there may be a way to create a
logger()
extension function without having to explicitly call it with
<>
etc.
h
Here they explain how you can create a bean and inject it in your classes. https://medium.com/simars/inject-loggers-in-spring-java-or-kotlin-87162d02d068