mirror of
https://github.com/SlimeVR/SlimeVR-Server.git
synced 2026-12-06 08:42:32 -08:00
Logger
This commit is contained in:
1 parent
ef83b28a41
commit
f0a8f07ea1
58 files changed
+3219
-577
No files matched your search
@@ -5,6 +5,7 @@ import dev.slimevr.config.AppConfig
|
||||
import dev.slimevr.firmware.FirmwareManager
|
||||
import dev.slimevr.heightcalibration.HeightCalibrationManager
|
||||
import dev.slimevr.keybind.KeybindManager
|
||||
import dev.slimevr.logging.LogSourceProvider
|
||||
import dev.slimevr.networkprofile.NetworkProfileManager
|
||||
import dev.slimevr.provisioning.ProvisioningManager
|
||||
import dev.slimevr.resets.ResetsManager
|
||||
@@ -54,6 +55,7 @@ interface AppContextProvider : Phase1ContextProvider {
|
||||
val resetsManager: ResetsManager
|
||||
val tapDetectionManager: TapDetectionManager
|
||||
val stepMountingManager: StepMountingManager
|
||||
val logSources: List<LogSourceProvider>
|
||||
fun startObserving()
|
||||
suspend fun dispose()
|
||||
}
|
||||
@@ -81,6 +83,7 @@ class AppContext(
|
||||
override val resetsManager: ResetsManager,
|
||||
override val tapDetectionManager: TapDetectionManager,
|
||||
override val stepMountingManager: StepMountingManager,
|
||||
override val logSources: List<LogSourceProvider>,
|
||||
) : AppContextProvider {
|
||||
override fun startObserving() {
|
||||
keybindManager.startObserving(this)
|
||||
|
||||
@@ -2,8 +2,6 @@ package dev.slimevr.config
|
||||
|
||||
fun reduce(state: SettingsState, action: SettingsActions): SettingsState = when (action) {
|
||||
is SettingsActions.Update -> state.copy(data = action.transform(state.data))
|
||||
|
||||
is SettingsActions.LoadProfile -> action.newState
|
||||
|
||||
is SettingsActions.Rename -> state.copy(name = action.name)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import io.klogging.sending.SendString
|
||||
import java.io.BufferedOutputStream
|
||||
import java.io.Closeable
|
||||
import java.io.DataOutputStream
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.nio.file.Path
|
||||
import java.time.LocalDateTime
|
||||
@@ -66,10 +67,13 @@ class LogFileSender(
|
||||
}
|
||||
}
|
||||
|
||||
private fun deleteLogsBeyond(directory: Path, keep: Int) = directory.toFile()
|
||||
/** Server log files in [directory], newest first, logs left by previous runs included. */
|
||||
fun listLogFiles(directory: Path): List<File> = directory.toFile()
|
||||
.listFiles().orEmpty()
|
||||
.filter { it.name.startsWith(LOG_TAG) && it.name.endsWith(LOG_SUFFIX) }
|
||||
.filter { it.isFile && it.name.startsWith(LOG_TAG) && it.name.endsWith(LOG_SUFFIX) }
|
||||
.sortedByDescending { it.lastModified() }
|
||||
|
||||
private fun deleteLogsBeyond(directory: Path, keep: Int) = listLogFiles(directory)
|
||||
.drop(keep)
|
||||
// A file another process still holds open cannot be deleted on Windows; retry on exit.
|
||||
.forEach { if (!it.delete()) it.deleteOnExit() }
|
||||
@@ -0,0 +1,28 @@
|
||||
package dev.slimevr.logging
|
||||
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import solarxr_protocol.rpc.LogEvent
|
||||
import solarxr_protocol.rpc.LogSource
|
||||
import java.io.InputStream
|
||||
|
||||
class LogFileEntry(
|
||||
val name: String,
|
||||
val size: Long,
|
||||
val modifiedMs: Long,
|
||||
val current: Boolean,
|
||||
val open: () -> InputStream,
|
||||
)
|
||||
|
||||
/** One place logs can be read from: this server, the OpenVR driver... */
|
||||
interface LogSourceProvider {
|
||||
val source: LogSource
|
||||
|
||||
/** Read on every request; a file name is only valid while it is in this list */
|
||||
fun files(): List<LogFileEntry>
|
||||
|
||||
/**
|
||||
* Starts with the events kept from before the subscription, oldest first, then follows new
|
||||
* ones. Null when the source only has files.
|
||||
*/
|
||||
val events: Flow<LogEvent>?
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package dev.slimevr.logging
|
||||
|
||||
import io.klogging.Level
|
||||
import io.klogging.rendering.evalTemplate
|
||||
import io.klogging.sending.EventSender
|
||||
import kotlinx.coroutines.channels.BufferOverflow
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.filter
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.flow.onSubscription
|
||||
import kotlinx.datetime.toStdlibInstant
|
||||
import solarxr_protocol.rpc.LogEvent
|
||||
import solarxr_protocol.rpc.LogLevel
|
||||
import solarxr_protocol.rpc.LogSource
|
||||
import io.klogging.events.LogEvent as KloggingEvent
|
||||
|
||||
const val BACKLOG_SIZE = 2000
|
||||
|
||||
/**
|
||||
* Room for events between a subscriber's reads. Without it, tryEmit from the logging thread
|
||||
* fails whenever a subscriber is not waiting at that instant, and the event is lost.
|
||||
*/
|
||||
private const val SUBSCRIBER_BUFFER = 1024
|
||||
|
||||
internal val ANSI_ESCAPE = Regex("\u001B\\[[0-9;]*m")
|
||||
|
||||
private class Entry(val seq: Long, val event: LogEvent)
|
||||
|
||||
/**
|
||||
* Klogging sink keeping the last [BACKLOG_SIZE] events of [source] and passing new ones to
|
||||
* subscribers of [events].
|
||||
*/
|
||||
class LogEventBuffer(private val source: LogSource) : EventSender {
|
||||
private val lock = Any()
|
||||
private val backlog = ArrayDeque<Entry>(BACKLOG_SIZE)
|
||||
private var nextSeq = 0L
|
||||
private val live = MutableSharedFlow<Entry>(
|
||||
extraBufferCapacity = SUBSCRIBER_BUFFER,
|
||||
onBufferOverflow = BufferOverflow.DROP_OLDEST,
|
||||
)
|
||||
|
||||
override fun invoke(batch: List<KloggingEvent>) = synchronized(lock) {
|
||||
for (event in batch) {
|
||||
val entry = Entry(nextSeq++, toLogEvent(source, event))
|
||||
if (backlog.size == BACKLOG_SIZE) backlog.removeFirst()
|
||||
backlog.addLast(entry)
|
||||
live.tryEmit(entry)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An event added between the subscription and the backlog snapshot reaches the subscriber
|
||||
* twice, once from each; the sequence number drops the second copy.
|
||||
*/
|
||||
val events: Flow<LogEvent> = flow {
|
||||
var lastSeq = -1L
|
||||
live
|
||||
.onSubscription { synchronized(lock) { backlog.toList() }.forEach { emit(it) } }
|
||||
.filter { it.seq > lastSeq }
|
||||
.collect {
|
||||
lastSeq = it.seq
|
||||
emit(it.event)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun toLogEvent(source: LogSource, event: KloggingEvent): LogEvent {
|
||||
val items = if (event.items.isNotEmpty()) " : ${event.items}" else ""
|
||||
return LogEvent(
|
||||
source = source,
|
||||
timeMs = event.timestamp.toStdlibInstant().toEpochMilliseconds().toULong(),
|
||||
level = toLogLevel(event.level),
|
||||
logger = event.logger,
|
||||
message = (event.evalTemplate() + items).replace(ANSI_ESCAPE, ""),
|
||||
stackTrace = event.stackTrace,
|
||||
)
|
||||
}
|
||||
|
||||
private fun toLogLevel(level: Level) = when (level) {
|
||||
Level.TRACE -> LogLevel.TRACE
|
||||
Level.DEBUG -> LogLevel.DEBUG
|
||||
Level.INFO, Level.NONE -> LogLevel.INFO
|
||||
Level.WARN -> LogLevel.WARN
|
||||
Level.ERROR -> LogLevel.ERROR
|
||||
Level.FATAL -> LogLevel.FATAL
|
||||
}
|
||||
@@ -7,7 +7,11 @@ import io.klogging.config.loggingConfiguration
|
||||
import io.klogging.logger
|
||||
import io.klogging.noCoLogger
|
||||
import io.klogging.rendering.RENDER_SIMPLE
|
||||
import io.klogging.rendering.RenderString
|
||||
import io.klogging.sending.EventSender
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import solarxr_protocol.rpc.LogEvent
|
||||
import solarxr_protocol.rpc.LogSource
|
||||
import java.nio.file.Path
|
||||
|
||||
object AppLogger {
|
||||
@@ -45,25 +49,54 @@ object AppLogger {
|
||||
}
|
||||
}
|
||||
|
||||
/** RENDER_SIMPLE without terminal colour codes, so the files are plain text. */
|
||||
private val RENDER_FILE = RenderString { RENDER_SIMPLE(it).replace(ANSI_ESCAPE, "") }
|
||||
|
||||
private const val CONSOLE_SINK = "console"
|
||||
private const val FILE_SINK = "file"
|
||||
private const val ERROR_REPORTS_SINK = "error-reports"
|
||||
private const val LOG_PAGE_SINK = "log-page"
|
||||
|
||||
private val errorReportsSender = EventSender { batch ->
|
||||
batch.forEach { reportLog(it.logger, it.level, it.message, it.stackTrace) }
|
||||
}
|
||||
|
||||
suspend fun configureLogging(consoleSink: SinkConfiguration, logDirectory: Path?, minLevel: Level = Level.INFO) {
|
||||
class ServerLogSource(
|
||||
buffer: LogEventBuffer,
|
||||
private val logDirectory: Path?,
|
||||
) : LogSourceProvider {
|
||||
override val source = LogSource.SLIMEVR_SERVER
|
||||
|
||||
override val events: Flow<LogEvent> = buffer.events
|
||||
|
||||
override fun files(): List<LogFileEntry> {
|
||||
val directory = logDirectory ?: return emptyList()
|
||||
return listLogFiles(directory).mapIndexed { index, file ->
|
||||
LogFileEntry(
|
||||
name = file.name,
|
||||
size = file.length(),
|
||||
modifiedMs = file.lastModified(),
|
||||
current = index == 0,
|
||||
open = { file.inputStream() },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun configureLogging(consoleSink: SinkConfiguration, logDirectory: Path?, minLevel: Level = Level.INFO): ServerLogSource {
|
||||
val fileSender = logDirectory?.let { runCatching { LogFileSender(it) } }
|
||||
val logPageBuffer = LogEventBuffer(LogSource.SLIMEVR_SERVER)
|
||||
|
||||
loggingConfiguration {
|
||||
sink(CONSOLE_SINK, consoleSink)
|
||||
fileSender?.getOrNull()?.let { sink(FILE_SINK, RENDER_SIMPLE, it) }
|
||||
fileSender?.getOrNull()?.let { sink(FILE_SINK, RENDER_FILE, it) }
|
||||
sink(ERROR_REPORTS_SINK, SinkConfiguration(eventSender = errorReportsSender))
|
||||
sink(LOG_PAGE_SINK, SinkConfiguration(eventSender = logPageBuffer))
|
||||
logging {
|
||||
fromMinLevel(minLevel) {
|
||||
toSink(CONSOLE_SINK)
|
||||
if (fileSender?.isSuccess == true) toSink(FILE_SINK)
|
||||
toSink(LOG_PAGE_SINK)
|
||||
}
|
||||
fromMinLevel(Level.WARN) { toSink(ERROR_REPORTS_SINK) }
|
||||
}
|
||||
@@ -83,4 +116,6 @@ suspend fun configureLogging(consoleSink: SinkConfiguration, logDirectory: Path?
|
||||
}
|
||||
|
||||
captureStandardStreams()
|
||||
|
||||
return ServerLogSource(logPageBuffer, logDirectory?.takeIf { fileSender?.isSuccess == true })
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import dev.slimevr.solarxr.rpc.HeightCalibrationBehaviour
|
||||
import dev.slimevr.solarxr.rpc.InstalledInfoBehaviour
|
||||
import dev.slimevr.solarxr.rpc.KeybindsBehaviour
|
||||
import dev.slimevr.solarxr.rpc.KnownTrackersBehaviour
|
||||
import dev.slimevr.solarxr.rpc.LogsBehaviour
|
||||
import dev.slimevr.solarxr.rpc.MagBehaviour
|
||||
import dev.slimevr.solarxr.rpc.ProfilesBehaviour
|
||||
import dev.slimevr.solarxr.rpc.ProvisioningBehaviour
|
||||
@@ -209,6 +210,7 @@ class SolarXRBridge(
|
||||
add(DongleSettingsBehaviour(appContext.server))
|
||||
add(TelemetryBehaviour(appContext.server))
|
||||
add(TrackerImuTelemetryBehaviour(appContext.server))
|
||||
add(LogsBehaviour(appContext.logSources))
|
||||
add(DriverHandshakeBehaviour(appContext))
|
||||
add(DriverOutgoingTrackersBehaviour(appContext))
|
||||
add(DriverIncomingTrackersBehaviour(appContext))
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package dev.slimevr.solarxr.rpc
|
||||
|
||||
import dev.slimevr.logging.LogSourceProvider
|
||||
import dev.slimevr.solarxr.SolarXRBridge
|
||||
import dev.slimevr.solarxr.SolarXRBridgeBehaviour
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.cancelAndJoin
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.channelFlow
|
||||
import kotlinx.coroutines.flow.merge
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import solarxr_protocol.rpc.LogEvent
|
||||
import solarxr_protocol.rpc.LogFile
|
||||
import solarxr_protocol.rpc.LogFileChunkRequest
|
||||
import solarxr_protocol.rpc.LogFileChunkResponse
|
||||
import solarxr_protocol.rpc.LogSourceInfo
|
||||
import solarxr_protocol.rpc.LogStreamRequest
|
||||
import solarxr_protocol.rpc.LogStreamResponse
|
||||
import solarxr_protocol.rpc.LogsRequest
|
||||
import solarxr_protocol.rpc.LogsResponse
|
||||
import java.io.InputStream
|
||||
import kotlin.time.Duration
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
|
||||
private val BATCH_WINDOW = 100.milliseconds
|
||||
private const val CHUNK_SIZE = 128 * 1024
|
||||
|
||||
private fun readChunk(input: InputStream, offset: Long): ByteArray {
|
||||
var toSkip = offset
|
||||
while (toSkip > 0) {
|
||||
val skipped = input.skip(toSkip)
|
||||
if (skipped <= 0) return ByteArray(0)
|
||||
toSkip -= skipped
|
||||
}
|
||||
|
||||
val buffer = ByteArray(CHUNK_SIZE)
|
||||
var read = 0
|
||||
while (read < CHUNK_SIZE) {
|
||||
val n = input.read(buffer, read, CHUNK_SIZE - read)
|
||||
if (n < 0) break
|
||||
read += n
|
||||
}
|
||||
return if (read == CHUNK_SIZE) buffer else buffer.copyOf(read)
|
||||
}
|
||||
|
||||
private fun batchByTime(events: Flow<LogEvent>, window: Duration): Flow<List<LogEvent>> = channelFlow {
|
||||
val pending = Channel<LogEvent>(Channel.UNLIMITED)
|
||||
launch { events.collect { pending.send(it) } }
|
||||
for (first in pending) {
|
||||
delay(window)
|
||||
val batch = mutableListOf(first)
|
||||
while (true) batch += pending.tryReceive().getOrNull() ?: break
|
||||
send(batch)
|
||||
}
|
||||
}
|
||||
|
||||
class LogsBehaviour(private val sources: List<LogSourceProvider>) : SolarXRBridgeBehaviour {
|
||||
override fun observe(receiver: SolarXRBridge) {
|
||||
var streamJob: Job? = null
|
||||
|
||||
receiver.rpcDispatcher.on<LogsRequest> {
|
||||
val infos = sources.map { LogSourceInfo(source = it.source, live = it.events != null) }
|
||||
val files = withContext(Dispatchers.IO) {
|
||||
sources.flatMap { provider ->
|
||||
provider.files().map {
|
||||
LogFile(
|
||||
source = provider.source,
|
||||
name = it.name,
|
||||
size = it.size.toULong(),
|
||||
modifiedMs = it.modifiedMs.toULong(),
|
||||
current = it.current,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
receiver.sendRpc(LogsResponse(sources = infos, files = files))
|
||||
}.launchIn(receiver.context.scope)
|
||||
|
||||
receiver.rpcDispatcher.on<LogStreamRequest> { req ->
|
||||
streamJob?.cancelAndJoin()
|
||||
val requested = req.sources.orEmpty().toSet()
|
||||
val flows = sources.filter { it.source in requested }.mapNotNull { it.events }
|
||||
streamJob = if (flows.isEmpty()) {
|
||||
null
|
||||
} else {
|
||||
receiver.context.scope.launch {
|
||||
batchByTime(flows.merge(), BATCH_WINDOW).collect { batch ->
|
||||
receiver.sendRpc(LogStreamResponse(events = batch))
|
||||
}
|
||||
}
|
||||
}
|
||||
}.launchIn(receiver.context.scope)
|
||||
|
||||
receiver.rpcDispatcher.on<LogFileChunkRequest> { req ->
|
||||
val entry = withContext(Dispatchers.IO) {
|
||||
sources.firstOrNull { it.source == req.source }?.files()?.firstOrNull { it.name == req.name }
|
||||
}
|
||||
val data = entry?.let { withContext(Dispatchers.IO) { it.open().use { input -> readChunk(input, req.offset.toLong()) } } }
|
||||
receiver.sendRpc(
|
||||
LogFileChunkResponse(
|
||||
source = req.source,
|
||||
name = req.name,
|
||||
offset = req.offset,
|
||||
data = data?.asList()?.map { it.toUByte() },
|
||||
eof = data == null || data.size < CHUNK_SIZE,
|
||||
),
|
||||
)
|
||||
}.launchIn(receiver.context.scope)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user