From fd1b47014a6b95aba297cda1476bfd6495c453a3 Mon Sep 17 00:00:00 2001 From: Cedrick Cooke Date: Tue, 7 May 2024 09:16:07 -0700 Subject: [PATCH] Add `synchronized` extension function for Loggers (#40) --- khronicle-core/api/khronicle-core.api | 4 ++ .../commonMain/kotlin/SynchronizedLogger.kt | 37 +++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 khronicle-core/src/commonMain/kotlin/SynchronizedLogger.kt diff --git a/khronicle-core/api/khronicle-core.api b/khronicle-core/api/khronicle-core.api index 8620a83..197488d 100644 --- a/khronicle-core/api/khronicle-core.api +++ b/khronicle-core/api/khronicle-core.api @@ -140,6 +140,10 @@ public abstract class com/juul/khronicle/SimpleLogger : com/juul/khronicle/Logge public final fun warn (Ljava/lang/String;Ljava/lang/String;Lcom/juul/khronicle/ReadMetadata;Ljava/lang/Throwable;)V } +public final class com/juul/khronicle/SynchronizedLoggerKt { + public static final fun synchronized (Lcom/juul/khronicle/Logger;)Lcom/juul/khronicle/Logger; +} + public abstract interface class com/juul/khronicle/TagGenerator { public abstract fun getTag ()Ljava/lang/String; } diff --git a/khronicle-core/src/commonMain/kotlin/SynchronizedLogger.kt b/khronicle-core/src/commonMain/kotlin/SynchronizedLogger.kt new file mode 100644 index 0000000..32c30f4 --- /dev/null +++ b/khronicle-core/src/commonMain/kotlin/SynchronizedLogger.kt @@ -0,0 +1,37 @@ +package com.juul.khronicle + +import kotlinx.atomicfu.locks.reentrantLock +import kotlinx.atomicfu.locks.withLock + +public fun Logger.synchronized(): Logger = SynchronizedLogger(this) + +private class SynchronizedLogger( + private val inner: Logger, +) : Logger { + + private val guard = reentrantLock() + + override fun verbose(tag: String, message: String, metadata: ReadMetadata, throwable: Throwable?) { + guard.withLock { inner.verbose(tag, message, metadata, throwable) } + } + + override fun debug(tag: String, message: String, metadata: ReadMetadata, throwable: Throwable?) { + guard.withLock { inner.debug(tag, message, metadata, throwable) } + } + + override fun info(tag: String, message: String, metadata: ReadMetadata, throwable: Throwable?) { + guard.withLock { inner.info(tag, message, metadata, throwable) } + } + + override fun warn(tag: String, message: String, metadata: ReadMetadata, throwable: Throwable?) { + guard.withLock { inner.warn(tag, message, metadata, throwable) } + } + + override fun error(tag: String, message: String, metadata: ReadMetadata, throwable: Throwable?) { + guard.withLock { inner.error(tag, message, metadata, throwable) } + } + + override fun assert(tag: String, message: String, metadata: ReadMetadata, throwable: Throwable?) { + guard.withLock { inner.assert(tag, message, metadata, throwable) } + } +}