i'm trying to write my own logging utility. is the...
# announcements
w
i'm trying to write my own logging utility. is there anyway to use reified functions / extension functions to automatically get the calling classes name? something like
Copy code
// usage
MyLogger.log("foo")

// impl
inline fun <reified T : Any> T.log(msg: String) {
  // ...
  val caller = T::class.simpleName
}
n
why are you assuming it's called from a class?
n
the way logging frameworks normally do that is using
Thread.currentThread().stackTrace
2
c
Or you can just make it as an extension function from
Any
1
2
t
what's wrong with your example code? Shouldn't that already work?
f
what's wrong with your example code? Shouldn't
that already work?
No, his code will always have
MyLogger
as
caller
t
ah, I see. If you define it as an extension function on a reified parameter, you should just call it directly on the instance you want as caller, not on the MyLogger object.
s
this article presents several options on how logging can be done in Kotlin. It’s where I got my approach from: https://www.baeldung.com/kotlin-logging
👍 1
s
Baeldung is a great resource.
n
This class orientation to logging is kinda odd in a language that advocates using free functions when appropriate
Suggests having a file level logger
If you logger functions taking user lambdas are inlined and the lambda is reified, I believe you can ask the lambda which module/package it comes from
I have the code sitting somewhere
w
some of those paths wont work out outside of JVM