https://kotlinlang.org logo
#getting-started
Title
# getting-started
k

Kenneth

02/24/2023, 8:49 AM
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

CLOVIS

02/24/2023, 8:51 AM
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

Chris Lee

02/24/2023, 8:52 AM
k

Kenneth

02/24/2023, 8:58 AM
Typical sl4j with logback project
a

Adam S

02/24/2023, 9:37 AM
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

Kenneth

02/24/2023, 10:10 AM
Thanks for the suggestions, I will take a closer look at kotlin-logging.
e

ephemient

02/25/2023, 4:31 AM
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

Humphrey

02/25/2023, 6:42 PM
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