Another trick I used. Not sure if it’s faster or not. I didn’t store logger instance anywhere, in my benchmarks logback is very fast so it doesn’t make sense to store it IMO.
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.func
val lastDollarIndex = anchorClassName.lastIndexOf('$')
if (lastDollarIndex == -1 ) return anchorClassName
val prevLastDollarIndex = anchorClassName.lastIndexOf('$', startIndex = lastDollarIndex - 1)
if (prevLastDollarIndex == -1) return anchorClassName
return anchorClassName.substring(0, prevLastDollarIndex) + '.' +
anchorClassName.substring(prevLastDollarIndex + 1, lastDollarIndex)
}
return LoggerFactory.getLogger(getLoggerName())
}
fun logTrace(message: () -> String) {
val logger = getFunctionLogger(message)
if (logger.isTraceEnabled) logger.trace(message())
}
Basically when you’re using logTrace
, you passing lambda which is instance of anonymous Java class and its name could be used to create logger name.