Fix produced log events having wrong data when log message has newlines

This commit is contained in:
Sapphire committed 2026-12-06 06:23:05 -05:00
1 parent 0ebf7be578
commit d09ad6e18d
1 file changed
+26 -9
@@ -81,14 +81,35 @@ private fun tailLogFile(source: LogSource, path: Path): Flow<LogEvent> = flow {
return complete.drop(1)
}
readNewLines().takeLast(BACKLOG_SIZE).forEach { line -> lineEvent(source, line)?.let { emit(it) } }
// If a line is invalid, it is likely from a single event that has newlines in the message
// Reuse the time and log level from the last line event
var lastEvent: LogEvent? = null
val emitLogEvent = suspend emitLogEvent@{ raw: String ->
val line = raw.trimEnd('\r')
if (line.isEmpty()) return@emitLogEvent
val event = lineEvent(source, line)?.also { lastEvent = it } ?: run {
lastEvent?.let { event ->
LogEvent(
source = source,
timeMs = event.timeMs,
level = event.level,
logger = event.logger,
message = line,
)
} ?: return@emitLogEvent
}
emit(event)
}
readNewLines().takeLast(BACKLOG_SIZE).forEach { line -> emitLogEvent(line) }
while (true) {
val key = runInterruptible { watcher.take() }
val touched = key.pollEvents().any { (it.context() as? Path)?.fileName == path.fileName }
key.reset()
if (!touched) continue
readNewLines().forEach { line -> lineEvent(source, line)?.let { emit(it) } }
readNewLines().forEach { line -> emitLogEvent(line) }
}
}
}.flowOn(Dispatchers.IO)
@@ -114,14 +135,10 @@ private fun readFrom(path: Path, offset: Long): Pair<String, Long> {
}
}
private fun lineEvent(source: LogSource, raw: String): LogEvent? {
val line = raw.trimEnd('\r')
if (line.isEmpty()) return null
val match = DRIVER_LINE.matchEntire(line)
?: return LogEvent(source = source, timeMs = System.currentTimeMillis().toULong(), level = LogLevel.INFO, logger = "", message = line)
private fun lineEvent(source: LogSource, line: String): LogEvent? {
val match = DRIVER_LINE.matchEntire(line) ?: return null
val (time, offset, level, message) = match.destructured
val zone = if (offset.isEmpty()) ZoneId.systemDefault() else ZoneOffset.of(offset)
return LogEvent(
source = source,