From a1aa04a993b944dfedcafc515d4b053ee217d95c Mon Sep 17 00:00:00 2001 From: George Smyrnaios Date: Fri, 18 Oct 2024 08:41:46 +0200 Subject: [PATCH] Add parallel processing for appender events Introduced a `forEachParallel` extension function to run operations concurrently on collections using coroutines. Updated `RootLogger` to utilize this extension, improving efficiency in appender event processing. --- .../kotlin/io/github/smyrgeorge/log4k/RootLogger.kt | 3 ++- .../github/smyrgeorge/log4k/impl/extensions/iterable.kt | 9 +++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 log4k/src/commonMain/kotlin/io/github/smyrgeorge/log4k/impl/extensions/iterable.kt diff --git a/log4k/src/commonMain/kotlin/io/github/smyrgeorge/log4k/RootLogger.kt b/log4k/src/commonMain/kotlin/io/github/smyrgeorge/log4k/RootLogger.kt index a175c001..f2881562 100644 --- a/log4k/src/commonMain/kotlin/io/github/smyrgeorge/log4k/RootLogger.kt +++ b/log4k/src/commonMain/kotlin/io/github/smyrgeorge/log4k/RootLogger.kt @@ -2,6 +2,7 @@ package io.github.smyrgeorge.log4k import io.github.smyrgeorge.log4k.impl.SimpleLoggerFactory import io.github.smyrgeorge.log4k.impl.appenders.ConsoleAppender +import io.github.smyrgeorge.log4k.impl.extensions.forEachParallel import io.github.smyrgeorge.log4k.registry.AppenderRegistry import io.github.smyrgeorge.log4k.registry.LoggerRegistry import kotlinx.coroutines.CoroutineScope @@ -31,7 +32,7 @@ object RootLogger { LoggerScope.launch(Dispatchers.IO) { events.consumeEach { event -> event.id = nextIdx() - appenders.all().forEach { it.append(event) } + appenders.all().forEachParallel { it.append(event) } } } } diff --git a/log4k/src/commonMain/kotlin/io/github/smyrgeorge/log4k/impl/extensions/iterable.kt b/log4k/src/commonMain/kotlin/io/github/smyrgeorge/log4k/impl/extensions/iterable.kt new file mode 100644 index 00000000..093b5f07 --- /dev/null +++ b/log4k/src/commonMain/kotlin/io/github/smyrgeorge/log4k/impl/extensions/iterable.kt @@ -0,0 +1,9 @@ +package io.github.smyrgeorge.log4k.impl.extensions + +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.withContext +import kotlin.coroutines.EmptyCoroutineContext + +suspend fun Iterable.forEachParallel(f: suspend (A) -> Unit): Unit = + withContext(EmptyCoroutineContext) { map { async { f(it) } }.awaitAll() } \ No newline at end of file