Files
GaCyGO-Android/app/src/main/java/com/gacy/android/service/LogBuffer.kt
T

54 lines
1.7 KiB
Kotlin

package com.gacy.android.service
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
object LogBuffer {
private const val MAX_LOG_LINES = 500
private const val MAX_DIAGNOSTIC_LINES = 100
private val timeFormat = SimpleDateFormat("HH:mm:ss", Locale.getDefault())
private val diagnostics = ArrayDeque<String>()
private val _logs = MutableStateFlow<List<String>>(emptyList())
val logs: StateFlow<List<String>> = _logs.asStateFlow()
@Synchronized
fun append(message: String) {
val timestamp = timeFormat.format(Date())
val formatted = "[$timestamp] $message"
if (isDiagnostic(message)) {
diagnostics.addLast(formatted)
if (diagnostics.size > MAX_DIAGNOSTIC_LINES) diagnostics.removeFirst()
}
val current = _logs.value.toMutableList()
current.add(formatted)
if (current.size > MAX_LOG_LINES) {
current.removeAt(0)
}
_logs.value = current
}
@Synchronized
fun clear() {
_logs.value = emptyList()
diagnostics.clear()
}
@Synchronized
fun getAllText(): String {
val recent = _logs.value
val olderDiagnostics = diagnostics.filterNot { it in recent }
return (olderDiagnostics + recent).joinToString("\n")
}
private fun isDiagnostic(message: String): Boolean =
"[gateway]" in message || "[DISPATCH]" in message ||
"[KCP] handshake rejected:" in message || "[KCP] packet rejected:" in message ||
"New connection from addr:" in message || "[Server error]" in message
}