Skip to content

Commit

Permalink
slf4j bridge - init lock with Semaphore
Browse files Browse the repository at this point in the history
  • Loading branch information
justcoon committed Nov 22, 2023
1 parent 3251d5a commit 05a5f71
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 29 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@
package zio.logging.slf4j.bridge

import org.slf4j.impl.ZioLoggerFactory
import zio.{ Runtime, ZIO, ZLayer }

import java.util.concurrent.locks.ReentrantLock
import zio.{ Runtime, Semaphore, Unsafe, ZIO, ZLayer }

object Slf4jBridge {

Expand Down Expand Up @@ -48,18 +46,15 @@ object Slf4jBridge {
def initialize(nameAnnotationKey: String): ZLayer[Any, Nothing, Unit] =
Runtime.enableCurrentFiber ++ layer(nameAnnotationKey)

private val initLock: ReentrantLock = new ReentrantLock()
private val initLock = Semaphore.unsafe.make(1)(Unsafe.unsafe)

private def layer(nameAnnotationKey: String): ZLayer[Any, Nothing, Unit] =
ZLayer {
ZIO.runtime[Any].flatMap { runtime =>
ZIO.succeed {
initLock.lock()
try
ZioLoggerFactory.initialize(new ZioLoggerRuntime(runtime, nameAnnotationKey))
finally
initLock.unlock()
}
}
for {
runtime <- ZIO.runtime[Any]
_ <- initLock.withPermits(1) {
ZIO.succeed(ZioLoggerFactory.initialize(new ZioLoggerRuntime(runtime, nameAnnotationKey)))
}
} yield ()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,7 @@
*/
package zio.logging.slf4j.bridge

import zio.{ Runtime, ZIO, ZLayer }

import java.util.concurrent.locks.ReentrantLock
import zio.{ Runtime, Semaphore, Unsafe, ZIO, ZLayer }

object Slf4jBridge {

Expand All @@ -31,21 +29,20 @@ object Slf4jBridge {
*/
def initializeWithoutFiberRefPropagation: ZLayer[Any, Nothing, Unit] = layer

private val initLock: ReentrantLock = new ReentrantLock()
private val initLock = Semaphore.unsafe.make(1)(Unsafe.unsafe)

private def layer: ZLayer[Any, Nothing, Unit] =
ZLayer {
ZIO.runtime[Any].flatMap { runtime =>
ZIO.succeed {
initLock.lock()
try
org.slf4j.LoggerFactory
.getILoggerFactory()
.asInstanceOf[LoggerFactory]
.attacheRuntime(new ZioLoggerRuntime(runtime))
finally
initLock.unlock()
}
}
for {
runtime <- ZIO.runtime[Any]
_ <- initLock.withPermits(1) {
ZIO.succeed(
org.slf4j.LoggerFactory
.getILoggerFactory()
.asInstanceOf[LoggerFactory]
.attacheRuntime(new ZioLoggerRuntime(runtime))
)
}
} yield ()
}
}

0 comments on commit 05a5f71

Please sign in to comment.