Yokan / rebuild
Course 1 8624561

LogSink.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/logging/LogSink.kt

implementation150 lines
1package eu.friedcutlet.yokan.services.logging23import eu.friedcutlet.yokan.util.nowMillis4import eu.friedcutlet.yokan.util.PlatformLock5import eu.friedcutlet.yokan.services.files.LocalFileService6import kotlin.concurrent.Volatile7import kotlin.time.ExperimentalTime8import kotlin.time.Instant9import kotlinx.datetime.TimeZone10import kotlinx.datetime.toLocalDateTime1112/** [seq] is unique and increasing for the process, so UIs can key rows by it. */13internal data class LogEntry(val seq: Long, val timeMillis: Long, val level: String, val message: String) {14    fun format(): String = "${formatLogTimestamp(timeMillis)} $level: $message"15}1617/**18 * Single sink for every log line produced by [AppLogger], `ExtensionLogger`,19 * and the HTTP-request logger. Secrets matching [CrashReportStore.redact] are masked first.20 *21 * Behavior:22 *  - Always println to stdout, so logs are visible in the platform console23 *    (terminal on desktop, `adb logcat -s System.out` on Android, Xcode24 *    console on iOS).25 *  - Keeps the last [MaxRecentEntries] lines, plus the last [MaxProblemEntries] warnings and26 *    errors, in memory for the Developer settings screen.27 *  - Once [attach]ed and while the file-logging setting is on (off by default),28 *    also appends to `LocalFileService.cacheRoot/logs/yokan.log`. When that file passes29 *    [MaxLogFileBytes] it becomes `yokan.log.1` (replacing the previous one), so logs on disk30 *    never exceed about twice that size.31 */32internal object LogSink {3334    private const val LOG_RELATIVE_PATH = "logs/yokan.log"35    const val MaxLogFileBytes = 1024L * 102436    const val MaxRecentEntries = 50037    const val MaxProblemEntries = 20038    private const val MaxLogMessageChars = 16 * 102439    private const val TruncatedMessageMarker = "…[truncated]"40    private val fileLock = PlatformLock()41    private val memoryLock = PlatformLock()42    private val recent = ArrayDeque<LogEntry>(MaxRecentEntries)43    private val problems = ArrayDeque<LogEntry>(MaxProblemEntries)44    private var nextSeq = 0L4546    private class FileTarget(val files: LocalFileService, val path: String, val enabled: () -> Boolean) {47        /** Unknown until the first append in this process; then tracked without touching the disk. */48        var sizeBytes = -1L49    }5051    // Set once by the composition root; until then lines only reach stdout and memory.52    @Volatile53    private var target: FileTarget? = null5455    /** [fileLoggingEnabled] runs for every line, so it must be cheap and must not take locks. */56    fun attach(files: LocalFileService, fileLoggingEnabled: () -> Boolean): Any? {57        val path = runCatching { "${files.cacheRoot.trimEnd('/')}/$LOG_RELATIVE_PATH" }.getOrNull() ?: return null58        return fileLock.withLock { FileTarget(files, path, fileLoggingEnabled).also { target = it } }59    }6061    /** Retiring an old owner cannot detach a later session's file target. */62    fun detach(token: Any?) = fileLock.withLock {63        if (target === token) target = null64    }6566    fun write(level: String, message: String) {67        val redacted = CrashReportStore.redact(message)68        val boundedMessage = if (redacted.length > MaxLogMessageChars) {69            redacted.take(MaxLogMessageChars - TruncatedMessageMarker.length) + TruncatedMessageMarker70        } else {71            redacted72        }73        val entry = memoryLock.withLock {74            LogEntry(nextSeq++, nowMillis(), level.take(32), boundedMessage).also {75                recent.addBounded(it, MaxRecentEntries)76                if (level != "INFO") problems.addBounded(it, MaxProblemEntries)77            }78        }79        val line = entry.format()80        println("[yokan] $line")81        val sink = target ?: return82        if (runCatching(sink.enabled).getOrDefault(false)) {83            fileLock.withLock {84                if (target !== sink) return@withLock85                runCatching { sink.sizeBytes = appendRotatingLog(sink.files, sink.path, sink.sizeBytes, (line + "\n").encodeToByteArray()) }86            }87        }88    }8990    fun recentEntries(): List<LogEntry> = memoryLock.withLock { recent.toList() }91    fun problemEntries(): List<LogEntry> = memoryLock.withLock { problems.toList() }9293    fun clearMemory() {94        memoryLock.withLock {95            recent.clear()96            problems.clear()97        }98    }99100    /** Returns the path of the on-disk log file, regardless of whether logging is on. */101    fun logFilePath(): String? = target?.path102103    /** Bytes currently on disk for the log and its rotated predecessor. */104    fun logFileBytes(): Long {105        val sink = target ?: return 0L106        return fileLock.withLock {107            runCatching { sink.files.directorySize(sink.path) + sink.files.directorySize(rotatedLogPath(sink.path)) }.getOrDefault(0L)108        }109    }110111    private fun <T> ArrayDeque<T>.addBounded(value: T, max: Int) {112        if (size == max) removeFirst()113        addLast(value)114    }115}116117@OptIn(ExperimentalTime::class)118internal fun formatLogTimestamp(timeMillis: Long): String {119    val local = Instant.fromEpochMilliseconds(timeMillis).toLocalDateTime(TimeZone.currentSystemDefault())120    return buildString {121        append(local.year.toString().padStart(4, '0'))122        append('-')123        append((local.month.ordinal + 1).toString().padStart(2, '0'))124        append('-')125        append(local.day.toString().padStart(2, '0'))126        append(' ')127        append(local.hour.toString().padStart(2, '0'))128        append(':')129        append(local.minute.toString().padStart(2, '0'))130        append(':')131        append(local.second.toString().padStart(2, '0'))132    }133}134135internal fun rotatedLogPath(path: String) = "$path.1"136137/**138 * Appends [bytes] to [path] (streaming; the history is never read), first moving the file to139 * [rotatedLogPath] when the append would pass [maxBytes]. [knownSize] < 0 means "stat the file";140 * returns the size after the append so callers can track it without touching the disk.141 */142internal fun appendRotatingLog(files: LocalFileService, path: String, knownSize: Long, bytes: ByteArray, maxBytes: Long = LogSink.MaxLogFileBytes): Long {143    val size = if (knownSize < 0) files.directorySize(path) else knownSize144    if (bytes.size.toLong() > maxBytes) return size145    val exceedsCap = size > 0 && size > maxBytes - bytes.size146    if (exceedsCap && !files.promote(path, rotatedLogPath(path))) return size147    val base = if (exceedsCap) 0L else size148    files.appendBytes(path, bytes)149    return base + bytes.size150}151

Search chapters, reference and source filenames.