diff --git a/fleet/util/logging/api/srcCommonMain/fleet/util/logging/KLoggerFactory.kt b/fleet/util/logging/api/srcCommonMain/fleet/util/logging/KLoggerFactory.kt index d97116349b16..782aeb3679d2 100644 --- a/fleet/util/logging/api/srcCommonMain/fleet/util/logging/KLoggerFactory.kt +++ b/fleet/util/logging/api/srcCommonMain/fleet/util/logging/KLoggerFactory.kt @@ -1,17 +1,27 @@ // Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package fleet.util.logging +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ThreadContextElement +import kotlinx.coroutines.withContext +import kotlin.collections.plus import kotlin.coroutines.CoroutineContext +import kotlin.coroutines.coroutineContext import kotlin.reflect.KClass interface KLoggerFactory { - fun logger(owner: KClass<*>): KLogger - fun logger(owner: Any): KLogger - fun logger(name: String): KLogger + fun logger(owner: KClass<*>): KLogger + fun logger(owner: Any): KLogger + fun logger(name: String): KLogger - fun setLoggingContext(map: Map?) - fun getLoggingContext(): Map? + fun setLoggingContext(map: Map?) + fun getLoggingContext(): Map? +} + +suspend fun withAdditionalLoggingContext(addition: Map, body: suspend CoroutineScope.() -> T): T { + val currentContext = coroutineContext[LoggingContextContextElement]?.contextMap ?: emptyMap() + val newContext = LoggingContextContextElement(currentContext + addition) + return withContext(newContext, body) } class LoggingContextContextElement(val contextMap: Map?) : ThreadContextElement?> { @@ -28,4 +38,5 @@ class LoggingContextContextElement(val contextMap: Map?) : Threa override val key: CoroutineContext.Key<*> get() = LoggingContextContextElement companion object : CoroutineContext.Key -} \ No newline at end of file +} +