Scoop API

scoop:scoop.log.console:0.1.0

src/provider.scoop

Selected production source · src/provider.scoop

1package scoop.log.console
3import scoop.log.*
4import scoop.platform.concurrent.Mutex
5import scoop.platform.io.*
6import scoop.platform.time.SystemClock
7import scoop.time.Clock
8import scoop.time.Instant
10/** A borrowed process standard stream. Providers never close these descriptors. */
11public enum ConsoleStream {
12 /** The process standard output stream. */
13 Stdout,
14 /** The process standard error stream. */
15 Stderr
18private 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 }
37private fun severity(level: LogLevel): Int = when (level) {
38 case LogLevel.Trace -> 0
39 case LogLevel.Debug -> 1
40 case LogLevel.Info -> 2
41 case LogLevel.Warn -> 3
42 case LogLevel.Error -> 4
45/**
46 * Synchronously writes complete UTF-8 records to a borrowed standard stream. Instances writing
47 * the same stream share a lock. The clock and formatter run outside the lock and may run concurrently.
48 */
49public 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 = ::defaultConsoleLogFormat
54) : 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) }