How get package name inside a Kotlin file?


#1

Is it possible to get a Package or Class reference inside a Kotlin file?

package test

private val log = Logger.getLogger(package.name) // ?

// other functions...

#2

I did it with a little trick:

fun logTrace(message: () -> String) {
  val logger = getFunctionLogger(message)
  if (logger.isTraceEnabled) logger.trace(message())
}

private fun getFunctionLogger(anchorFunction: () -> String): Logger {
  fun getLoggerName(): String {
    val anchorClassName = anchorFunction.javaClass.name
    // anchorClassName: my.pckg.FileKt$func$1, we should return my.pckg.FileKt.f
unc
    val lastDollarIndex = anchorClassName.lastIndexOf('$')
    if (lastDollarIndex == -1 ) return anchorClassName
    val prevLastDollarIndex = anchorClassName.lastIndexOf('$', startIndex = last
DollarIndex - 1)
    if (prevLastDollarIndex == -1) return anchorClassName
    return anchorClassName.substring(0, prevLastDollarIndex) + '.' +
        anchorClassName.substring(prevLastDollarIndex + 1, lastDollarIndex)
  }
  return LoggerFactory.getLogger(getLoggerName())
}

You should use it like logTrace { "something here" }.

If you want a static logger instance, you can apply similar approach and write something like val log = getLogger {}, where {} is an empty no-op closure residing in a target package.