scoop:scoop.log.console:0.1.0
src/provider.scoop
Selected production source · src/provider.scoop
1
package scoop.log.console3
import scoop.log.*4
import scoop.platform.concurrent.Mutex5
import scoop.platform.io.*6
import scoop.platform.time.SystemClock7
import scoop.time.Clock8
import scoop.time.Instant10
/** A borrowed process standard stream. Providers never close these descriptors. */11
public enum ConsoleStream {12
/** The process standard output stream. */13
Stdout,14
/** The process standard error stream. */15
Stderr16
}18
private object ConsoleOutput {19
private val stdoutMutex: Mutex = Mutex()20
private val stderrMutex: Mutex = Mutex()22
fun write(stream: ConsoleStream, text: String) {23
when (stream) {24
case ConsoleStream.Stdout -> stdoutMutex.withLock { standardOutput.writeText(text) }25
case ConsoleStream.Stderr -> stderrMutex.withLock { standardError.writeText(text) }26
}27
}29
fun flush(stream: ConsoleStream) {30
when (stream) {31
case ConsoleStream.Stdout -> stdoutMutex.withLock { standardOutput.flush() }32
case ConsoleStream.Stderr -> stderrMutex.withLock { standardError.flush() }33
}34
}35
}37
private fun severity(level: LogLevel): Int = when (level) {38
case LogLevel.Trace -> 039
case LogLevel.Debug -> 140
case LogLevel.Info -> 241
case LogLevel.Warn -> 342
case LogLevel.Error -> 443
}45
/**46
* Synchronously writes complete UTF-8 records to a borrowed standard stream. Instances writing47
* the same stream share a lock. The clock and formatter run outside the lock and may run concurrently.48
*/49
public class ConsoleLogProvider public constructor(50
private val stream: ConsoleStream = ConsoleStream.Stderr,51
private val minLevel: LogLevel = LogLevel.Info,52
private val clock: Clock = SystemClock,53
private val format: (LogRecord, Instant) -> String = ::defaultConsoleLogFormat54
) : LogProvider {55
/** Enables all targets at or above the configured minimum severity. */56
public override fun isEnabled(level: LogLevel, target: String): Boolean = severity(level) >= severity(minLevel)58
/** Formats an already enabled event, appends one LF, and completes the write before returning. */59
public override fun emit(record: LogRecord) {60
val timestamp = clock.now()61
val text = format(record, timestamp) + "\n"62
ConsoleOutput.write(stream, text)63
}65
/** Flushes the borrowed stream under the same lock as writes; standard streams are unbuffered. */66
public override fun flush() { ConsoleOutput.flush(stream) }67
}