Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Addressing points raised in detektJvmMain task #203

Merged
merged 3 commits into from
Dec 11, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions src/jvmMain/kotlin/mu/KLogger.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import org.slf4j.Logger
* logger.info{"this is $lazy evaluated string"}
*```
*/
@Suppress("TooManyFunctions")
public actual interface KLogger : Logger {

/**
Expand Down
44 changes: 16 additions & 28 deletions src/jvmMain/kotlin/mu/KotlinLoggingMDC.kt
Original file line number Diff line number Diff line change
Expand Up @@ -47,29 +47,20 @@ public inline fun <T> withLoggingContext(
body: () -> T
): T {
val pairForMDC = pair.filter { it.second != null }
val previousMDC = if (restorePrevious) {
pairForMDC.map { (k, _) ->
k to MDC.get(k)
val cleanupCallbacks = pairForMDC.map { (mdcKey, _) ->
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this is more readble

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code consolidates the cleanup logic in one place. Instead having an if-condition for restorePrevious both before and after the execution of the body payload, it's now only checked before the payload execution; afterwards, there's only one flow path: cleanupCallbacks executes whatever cleanup code it's been assigned.

val mdcValue = MDC.get(mdcKey)
if (restorePrevious && mdcValue != null) {
{ MDC.put(mdcKey, mdcValue) }
} else {
{ MDC.remove(mdcKey) }
}
} else {
null
}

try {
pairForMDC.forEach { MDC.put(it.first, it.second) }
return body()
} finally {
if (restorePrevious) {
previousMDC?.forEach {
if (it.second != null) {
MDC.put(it.first, it.second)
} else {
MDC.remove(it.first)
}
}
} else {
pairForMDC.forEach { MDC.remove(it.first) }
}
cleanupCallbacks.forEach { it.invoke() }
}
}

Expand All @@ -91,7 +82,14 @@ public inline fun <T> withLoggingContext(
restorePrevious: Boolean = true,
body: () -> T
): T {
val previousMDC = map.mapValues { MDC.get(it.key) }
val cleanupCallbacks = map.map {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same as above

val mdcValue = MDC.get(it.key)
if (restorePrevious && mdcValue != null) {
{ MDC.put(it.key, mdcValue) }
} else {
{ MDC.remove(it.key) }
}
}

try {
map.forEach {
Expand All @@ -101,16 +99,6 @@ public inline fun <T> withLoggingContext(
}
return body()
} finally {
if (restorePrevious) {
previousMDC.forEach {
if (it.value != null) {
MDC.put(it.key, it.value)
} else {
MDC.remove(it.key)
}
}
} else {
previousMDC.forEach { MDC.remove(it.key) }
}
cleanupCallbacks.forEach { it.invoke() }
}
}
20 changes: 7 additions & 13 deletions src/jvmMain/kotlin/mu/internal/KLoggerNameResolver.kt
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,12 @@ internal object KLoggerNameResolver {
* unwrap companion class to enclosing class given a Java Class
*/
private inline fun <T : Any> unwrapCompanionClass(clazz: Class<T>): Class<*> {
if (clazz.enclosingClass != null) {
try {
val field = clazz.enclosingClass.getDeclaredField(clazz.simpleName)
if (Modifier.isStatic(field.modifiers) && field.type == clazz) {
// && field.get(null) === obj
// the above might be safer but problematic with initialization order
return clazz.enclosingClass
}
} catch (e: Exception) {
//ok, it is not a companion object
}
}
return clazz
return clazz.enclosingClass?.let { enclosingClass ->
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I also don't see a good reason to change that

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Searching through declaredFields instead of using getDeclaredField() has the advantage of not throwing NoSuchFieldException if the declared field cannot be found. If there's a Kotlin-implemented version of this functionality that doesn't use reflection and handles the "field not found" case more gracefully than the Java-implemented version, I'd be glad to use that, but in general, it's better to avoid using exceptions as control flow when possible.

enclosingClass.declaredFields.find { field ->
field.name == clazz.simpleName &&
Modifier.isStatic(field.modifiers) &&
field.type == clazz
}?.run { enclosingClass }
} ?: clazz
}
}
3 changes: 2 additions & 1 deletion src/jvmMain/kotlin/mu/internal/LocationAwareKLogger.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import org.slf4j.spi.LocationAwareLogger
* A class wrapping a [LocationAwareLogger] instance preserving
* location information with the correct fully qualified class name.
*/
@Suppress("VariableNaming", "TooManyFunctions")
internal class LocationAwareKLogger(override val underlyingLogger: LocationAwareLogger) : KLogger,
Logger by underlyingLogger {

Expand Down Expand Up @@ -558,7 +559,7 @@ internal class LocationAwareKLogger(override val underlyingLogger: LocationAware
override fun entry(vararg argArray: Any?) {
if (underlyingLogger.isTraceEnabled(ENTRY)) {
val tp = MessageFormatter.arrayFormat(buildMessagePattern(argArray.size), argArray)
underlyingLogger.log(ENTRY, fqcn, LocationAwareLogger.TRACE_INT, tp.message, null, null);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice!

underlyingLogger.log(ENTRY, fqcn, LocationAwareLogger.TRACE_INT, tp.message, null, null)
}
}

Expand Down
1 change: 1 addition & 0 deletions src/jvmMain/kotlin/mu/internal/LocationIgnorantKLogger.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import org.slf4j.Marker
* the rest of the methods are delegated to [Logger]
* Hence no implemented methods
*/
@Suppress("TooManyFunctions")
internal class LocationIgnorantKLogger(override val underlyingLogger: Logger) : KLogger, Logger by underlyingLogger {

/**
Expand Down
43 changes: 43 additions & 0 deletions src/jvmTest/kotlin/mu/KotlinLoggingMDCTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -182,4 +182,47 @@ class KotlinLoggingMDCTest {
assertNull(MDC.get("f"))
assertEquals("l", MDC.get("k"))
}

@Test
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks!

fun `map withLoggingContext (restorePrevious=false)`() {
assertNull(MDC.get("a"))
assertNull(MDC.get("c"))
assertNull(MDC.get("e"))
assertNull(MDC.get("f"))
assertNull(MDC.get("k"))

MDC.put("e", "g")
MDC.put("k", "l")

withLoggingContext(
mapOf("a" to "b", "c" to "d", "e" to null, "f" to "h"),
restorePrevious = false,
) {
assertEquals("b", MDC.get("a"))
assertEquals("d", MDC.get("c"))
assertEquals("g", MDC.get("e"))
assertEquals("h", MDC.get("f"))
assertEquals("l", MDC.get("k"))

withLoggingContext(mapOf("a" to "b", "e" to "i", "f" to "j")) {
assertEquals("b", MDC.get("a"))
assertEquals("d", MDC.get("c"))
assertEquals("i", MDC.get("e"))
assertEquals("j", MDC.get("f"))
assertEquals("l", MDC.get("k"))
}

assertEquals("b", MDC.get("a"))
assertEquals("d", MDC.get("c"))
assertEquals("g", MDC.get("e"))
assertEquals("h", MDC.get("f"))
assertEquals("l", MDC.get("k"))
}

assertNull(MDC.get("a"))
assertNull(MDC.get("c"))
assertNull(MDC.get("e"))
assertNull(MDC.get("f"))
assertEquals("l", MDC.get("k"))
}
}