fix(log): ограниченная очередь лога, экспорт через неё же
This commit is contained in:
1 parent
017876d62e
commit
5db1bf4712
3 files changed
+56
-24
No files matched your search
@@ -1,5 +1,6 @@
|
|||||||
package com.freeturn.app.domain.proxy
|
package com.freeturn.app.domain.proxy
|
||||||
|
|
||||||
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.SupervisorJob
|
||||||
@@ -9,47 +10,52 @@ import java.io.File
|
|||||||
import java.text.SimpleDateFormat
|
import java.text.SimpleDateFormat
|
||||||
import java.util.Date
|
import java.util.Date
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Лог сессии на диске. Экранный буфер живёт в памяти и чистится на каждом старте, поэтому
|
* Лог сессии на диске. Экранный буфер живёт в памяти и чистится на каждом старте, поэтому
|
||||||
* разобрать инцидент, после которого пользователь перезапустил прокси, было нечем.
|
* разобрать инцидент, после которого пользователь перезапустил прокси, было нечем.
|
||||||
*
|
*
|
||||||
* Пишет отдельным потоком: строки приходят из горутин Go, блокировать их нельзя. Время
|
* Пишет отдельным потоком: строки приходят из горутин Go, блокировать их нельзя. Время
|
||||||
* форматируется там же - SimpleDateFormat не потокобезопасен.
|
* форматируется там же - SimpleDateFormat не потокобезопасен. Очистка и экспорт идут той
|
||||||
|
* же очередью: ротация и запись не пересекаются с чтением файлов.
|
||||||
*/
|
*/
|
||||||
internal class LogFile(dir: File) {
|
internal class LogFile(dir: File) {
|
||||||
|
|
||||||
private sealed interface Cmd {
|
private sealed interface Cmd {
|
||||||
data class Line(val at: Long, val text: String, val level: LogLevel) : Cmd
|
data class Line(val at: Long, val text: String, val level: LogLevel) : Cmd
|
||||||
data object Clear : Cmd
|
data object Clear : Cmd
|
||||||
|
class Export(val target: File, val done: CompletableDeferred<Boolean>) : Cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
private val current = File(dir, "session.log")
|
private val current = File(dir, "session.log")
|
||||||
private val previous = File(dir, "session.1.log")
|
private val previous = File(dir, "session.1.log")
|
||||||
private val queue = Channel<Cmd>(Channel.UNLIMITED)
|
private val queue = Channel<Cmd>(QUEUE_CAPACITY)
|
||||||
|
private val dropped = AtomicInteger(0)
|
||||||
|
private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||||
|
|
||||||
init {
|
init {
|
||||||
dir.mkdirs()
|
dir.mkdirs()
|
||||||
CoroutineScope(Dispatchers.IO + SupervisorJob()).launch { drain() }
|
scope.launch { drain() }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun append(message: String, level: LogLevel) {
|
fun append(message: String, level: LogLevel) {
|
||||||
queue.trySend(Cmd.Line(System.currentTimeMillis(), message, level))
|
if (queue.trySend(Cmd.Line(System.currentTimeMillis(), message, level)).isFailure) {
|
||||||
|
dropped.incrementAndGet()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Сразу в очередь, если есть место: строки, отправленные до очистки, должны встать до неё.
|
||||||
fun clear() {
|
fun clear() {
|
||||||
queue.trySend(Cmd.Clear)
|
if (queue.trySend(Cmd.Clear).isFailure) scope.launch { queue.send(Cmd.Clear) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Оба файла подряд, старый первым - хронология не должна рваться в середине. */
|
/** Оба файла подряд, старый первым - хронология не должна рваться в середине. */
|
||||||
fun export(target: File): Boolean = runCatching {
|
suspend fun export(target: File): Boolean {
|
||||||
target.outputStream().buffered().use { out ->
|
val done = CompletableDeferred<Boolean>()
|
||||||
listOf(previous, current).filter { it.exists() }.forEach { part ->
|
queue.send(Cmd.Export(target, done))
|
||||||
part.inputStream().use { it.copyTo(out) }
|
return done.await()
|
||||||
}
|
}
|
||||||
}
|
|
||||||
target.length() > 0
|
|
||||||
}.getOrDefault(false)
|
|
||||||
|
|
||||||
// Пачкой: ядро сыплет строками из нескольких горутин, открывать файл на каждую дорого.
|
// Пачкой: ядро сыплет строками из нескольких горутин, открывать файл на каждую дорого.
|
||||||
private suspend fun drain() {
|
private suspend fun drain() {
|
||||||
@@ -57,30 +63,48 @@ internal class LogFile(dir: File) {
|
|||||||
val batch = StringBuilder()
|
val batch = StringBuilder()
|
||||||
for (cmd in queue) {
|
for (cmd in queue) {
|
||||||
apply(cmd, stamp, batch)
|
apply(cmd, stamp, batch)
|
||||||
while (true) {
|
while (batch.length < MAX_BATCH_CHARS) {
|
||||||
val next = queue.tryReceive().getOrNull() ?: break
|
val next = queue.tryReceive().getOrNull() ?: break
|
||||||
apply(next, stamp, batch)
|
apply(next, stamp, batch)
|
||||||
}
|
}
|
||||||
if (batch.isNotEmpty()) {
|
flush(stamp, batch)
|
||||||
write(batch.toString())
|
|
||||||
batch.setLength(0)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun apply(cmd: Cmd, stamp: SimpleDateFormat, batch: StringBuilder) {
|
private fun apply(cmd: Cmd, stamp: SimpleDateFormat, batch: StringBuilder) {
|
||||||
when (cmd) {
|
when (cmd) {
|
||||||
|
is Cmd.Line -> batch.appendEntry(stamp, cmd.at, cmd.level, cmd.text)
|
||||||
is Cmd.Clear -> {
|
is Cmd.Clear -> {
|
||||||
batch.setLength(0)
|
batch.setLength(0)
|
||||||
runCatching { current.delete(); previous.delete() }
|
runCatching { current.delete(); previous.delete() }
|
||||||
}
|
}
|
||||||
is Cmd.Line -> batch
|
is Cmd.Export -> {
|
||||||
.append(stamp.format(Date(cmd.at))).append(' ')
|
flush(stamp, batch)
|
||||||
.append(cmd.level.tag()).append(' ')
|
cmd.done.complete(exportTo(cmd.target))
|
||||||
.append(cmd.text).append('\n')
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun flush(stamp: SimpleDateFormat, batch: StringBuilder) {
|
||||||
|
val lost = dropped.getAndSet(0)
|
||||||
|
if (lost > 0) {
|
||||||
|
val note = "Лог: потеряно $lost строк (переполнение очереди)"
|
||||||
|
batch.appendEntry(stamp, System.currentTimeMillis(), LogLevel.Warning, note)
|
||||||
|
}
|
||||||
|
if (batch.isEmpty()) return
|
||||||
|
write(batch.toString())
|
||||||
|
batch.setLength(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun exportTo(target: File): Boolean = runCatching {
|
||||||
|
target.outputStream().buffered().use { out ->
|
||||||
|
listOf(previous, current).filter { it.exists() }.forEach { part ->
|
||||||
|
part.inputStream().use { it.copyTo(out) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
target.length() > 0
|
||||||
|
}.getOrDefault(false)
|
||||||
|
|
||||||
private fun write(text: String) {
|
private fun write(text: String) {
|
||||||
runCatching {
|
runCatching {
|
||||||
if (current.length() > MAX_BYTES) {
|
if (current.length() > MAX_BYTES) {
|
||||||
@@ -91,6 +115,12 @@ internal class LogFile(dir: File) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun StringBuilder.appendEntry(stamp: SimpleDateFormat, at: Long, level: LogLevel, text: String) {
|
||||||
|
append(stamp.format(Date(at))).append(' ')
|
||||||
|
.append(level.tag()).append(' ')
|
||||||
|
.append(text).append('\n')
|
||||||
|
}
|
||||||
|
|
||||||
private fun LogLevel.tag(): String = when (this) {
|
private fun LogLevel.tag(): String = when (this) {
|
||||||
LogLevel.Error -> "E"
|
LogLevel.Error -> "E"
|
||||||
LogLevel.Warning -> "W"
|
LogLevel.Warning -> "W"
|
||||||
@@ -100,5 +130,7 @@ internal class LogFile(dir: File) {
|
|||||||
|
|
||||||
private companion object {
|
private companion object {
|
||||||
const val MAX_BYTES = 1_000_000L
|
const val MAX_BYTES = 1_000_000L
|
||||||
|
const val QUEUE_CAPACITY = 4_096
|
||||||
|
const val MAX_BATCH_CHARS = 256 * 1024
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -64,7 +64,7 @@ class ProxyLog(dir: File) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Собирает лог в [target] для отправки; false - писать было нечего. */
|
/** Собирает лог в [target] для отправки; false - писать было нечего. */
|
||||||
fun export(target: File): Boolean = file.export(target)
|
suspend fun export(target: File): Boolean = file.export(target)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ядро сыплет строками пачками из своих горутин: публикуем срез не чаще
|
* Ядро сыплет строками пачками из своих горутин: публикуем срез не чаще
|
||||||
|
|||||||
@@ -61,5 +61,5 @@ class ProxyViewModel(
|
|||||||
fun clearLogs() = log.clearAll()
|
fun clearLogs() = log.clearAll()
|
||||||
|
|
||||||
/** false - отправлять нечего. */
|
/** false - отправлять нечего. */
|
||||||
fun exportLogs(target: File): Boolean = log.export(target)
|
suspend fun exportLogs(target: File): Boolean = log.export(target)
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user