# How get package name inside a Kotlin file?

**URL:** <https://discuss.kotlinlang.org/t/how-get-package-name-inside-a-kotlin-file/4676>\
**Category:** Uncategorized\
**Created:** [September 21, 2017, 6:44am UTC](https://discuss.kotlinlang.org/t/how-get-package-name-inside-a-kotlin-file/4676 "2017-09-21T06:44:05Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![fvasco](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/fvasco/32/1961_2.png) [@fvasco](https://discuss.kotlinlang.org/u/fvasco)\
**Post date:** [September 21, 2017, 6:44am UTC](https://discuss.kotlinlang.org/t/how-get-package-name-inside-a-kotlin-file/4676/1 "2017-09-21T06:44:05Z")

</div>

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...

```

---

<div class="post-metadata">

**Author:** ![vbezhenar](https://avatars.discourse-cdn.com/v4/letter/v/35a633/32.png) [@vbezhenar](https://discuss.kotlinlang.org/u/vbezhenar)\
**Post date:** [September 21, 2017, 7:18am UTC](https://discuss.kotlinlang.org/t/how-get-package-name-inside-a-kotlin-file/4676/2 "2017-09-21T07:18:18Z")

</div>

I did it with a little trick:

```auto
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.
