@@ -26,8 +26,11 @@ import kotlin.random.Random
26
26
import kotlinx.coroutines.CoroutineScope
27
27
import kotlinx.coroutines.DelicateCoroutinesApi
28
28
import kotlinx.coroutines.GlobalScope
29
+ import kotlinx.coroutines.flow.Flow
29
30
import 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
31
34
32
35
internal interface Logger {
33
36
val name: String
@@ -67,7 +70,8 @@ internal object LoggerGlobals {
67
70
val logLevel =
68
71
MutableStateFlow (LogLevel .WARN ).also { logLevelFlow ->
69
72
val logger = Logger (" LogLevelChange" )
70
- @OptIn(DelicateCoroutinesApi ::class ) logger.logChanges(logLevelFlow, GlobalScope )
73
+ @OptIn(DelicateCoroutinesApi ::class )
74
+ logger.logChanges(logLevelFlow.value, logLevelFlow, GlobalScope )
71
75
}
72
76
73
77
inline fun Logger.debug (message : () -> Any? ) {
@@ -100,16 +104,21 @@ internal object LoggerGlobals {
100
104
// logging is enabled and no logs are produced, to at least confirm that debug logging has been
101
105
// enabled. Also, it will leave a "mark" in the logs when debug logging is _disabled_ to explain
102
106
// 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 )" )
111
120
}
112
121
}
113
- }
122
+ .launchIn(coroutineScope)
114
123
}
115
124
}
0 commit comments