Skip to content

Commit

Permalink
let all loggers use non-anonymous parent class names
Browse files Browse the repository at this point in the history
  • Loading branch information
angryziber committed May 24, 2024
1 parent 9daad64 commit 0576cfe
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Unreleased
* core: logger(name) is now accessible without a class instance context
* core: Any.logger() will now take the closest non-anonymous superclass
* server: errors.on<SomeException>(StatusCode) convenience reified function added
* jdbc: BaseCrudRepository.list() and by() now both have the suffix parameter
* jdbc: handle Postgres "cached plan must not change result type" exception by enabling autosave=conservative by default
Expand Down
9 changes: 8 additions & 1 deletion core/src/Logger.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,14 @@ package klite
import java.lang.System.Logger.Level.*

fun logger(name: String): System.Logger = System.getLogger(name)
fun Any.logger(): System.Logger = System.getLogger(javaClass.name)
fun Any.logger(): System.Logger = logger(nonAnonymousClassName())

internal fun Any.nonAnonymousClassName(): String {
var cls = javaClass
while (cls.isAnonymousClass) cls = cls.superclass
return cls.name
}

inline fun System.Logger.debug(msg: String) = log(DEBUG, msg)
inline fun System.Logger.info(msg: String) = log(INFO, msg)
inline fun System.Logger.warn(msg: String) = log(WARNING, msg)
Expand Down
18 changes: 18 additions & 0 deletions core/test/LoggerTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package klite

import ch.tutteli.atrium.api.fluent.en_GB.toBeAnInstanceOf
import ch.tutteli.atrium.api.fluent.en_GB.toEqual
import ch.tutteli.atrium.api.verbs.expect
import org.junit.jupiter.api.Test
import java.util.Date

class LoggerTest {
@Test fun name() {
expect(nonAnonymousClassName()).toEqual(LoggerTest::class.java.name)
expect(object: Date() {}.nonAnonymousClassName()).toEqual(Date::class.java.name)
}

@Test fun testLogger() {
expect(logger()).toBeAnInstanceOf<System.Logger>()
}
}
2 changes: 1 addition & 1 deletion server/src/klite/ErrorHandler.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ open class BusinessException(messageKey: String, cause: Throwable? = null): Exce
typealias ThrowableHandler<T> = HttpExchange.(e: T) -> ErrorResponse?

open class ErrorHandler {
private val log = logger(ErrorHandler::class.java.name)
private val log = logger()
private val handlers = mutableMapOf<KClass<out Throwable>, ThrowableHandler<Throwable>>()
private val statusCodes = mutableMapOf<KClass<out Throwable>, StatusCode>(
IllegalArgumentException::class to BadRequest,
Expand Down

0 comments on commit 0576cfe

Please sign in to comment.