@@ -26,8 +26,11 @@ import kotlin.random.Random
2626import kotlinx.coroutines.CoroutineScope
2727import kotlinx.coroutines.DelicateCoroutinesApi
2828import kotlinx.coroutines.GlobalScope
29+ import kotlinx.coroutines.flow.Flow
2930import kotlinx.coroutines.flow.MutableStateFlow
30- import kotlinx.coroutines.launch
31+ import kotlinx.coroutines.flow.getAndUpdate
32+ import kotlinx.coroutines.flow.launchIn
33+ import kotlinx.coroutines.flow.onEach
3134
3235internal interface Logger {
3336 val name: String
@@ -67,7 +70,8 @@ internal object LoggerGlobals {
6770 val logLevel =
6871 MutableStateFlow (LogLevel .WARN ).also { logLevelFlow ->
6972 val logger = Logger (" LogLevelChange" )
70- @OptIn(DelicateCoroutinesApi ::class ) logger.logChanges(logLevelFlow, GlobalScope )
73+ @OptIn(DelicateCoroutinesApi ::class )
74+ logger.logChanges(logLevelFlow.value, logLevelFlow, GlobalScope )
7175 }
7276
7377 inline fun Logger.debug (message : () -> Any? ) {
@@ -100,16 +104,21 @@ internal object LoggerGlobals {
100104 // logging is enabled and no logs are produced, to at least confirm that debug logging has been
101105 // enabled. Also, it will leave a "mark" in the logs when debug logging is _disabled_ to explain
102106 // why the debug logs stop.
103- private fun Logger.logChanges (flow : MutableStateFlow <LogLevel >, coroutineScope : CoroutineScope ) {
104- var previousLogLevel = flow.value
105- coroutineScope.launch {
106- flow.collect { newLogLevel: LogLevel ->
107- if (newLogLevel != previousLogLevel) {
108- val emitLogLevel = LogLevel .noisiestOf(newLogLevel, previousLogLevel)
109- log(null , emitLogLevel, " Log level changed to $newLogLevel (was $previousLogLevel )" )
110- previousLogLevel = newLogLevel
107+ private fun Logger.logChanges (
108+ initialLogLevel : LogLevel ,
109+ flow : Flow <LogLevel >,
110+ coroutineScope : CoroutineScope
111+ ) {
112+ val state = MutableStateFlow (initialLogLevel)
113+ log(null , initialLogLevel, " Log level set to $initialLogLevel " )
114+ flow
115+ .onEach { newLogLevel: LogLevel ->
116+ val oldLogLevel = state.getAndUpdate { newLogLevel }
117+ if (newLogLevel != oldLogLevel) {
118+ val emitLogLevel = LogLevel .noisiestOf(newLogLevel, oldLogLevel)
119+ log(null , emitLogLevel, " Log level changed to $newLogLevel (was $oldLogLevel )" )
111120 }
112121 }
113- }
122+ .launchIn(coroutineScope)
114123 }
115124}
0 commit comments