Skip to content

Commit

Permalink
fix: 修复logger相关错误
Browse files Browse the repository at this point in the history
  • Loading branch information
nullaqua committed Sep 17, 2024
1 parent b0d1023 commit 67dd967
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 45 deletions.
1 change: 0 additions & 1 deletion src/main/kotlin/subit/ForumBackend.kt
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@ fun main(args: Array<String>)
// 创建一个临时文件, 用于存储合并后的配置文件
val tempFile = File.createTempFile("resConfig", ".yaml")
tempFile.writeText(Yaml.encodeToString(resConfig))
println(tempFile.readText())

val resArgs = args1 + "-config=${tempFile.absolutePath}"

Expand Down
11 changes: 9 additions & 2 deletions src/main/kotlin/subit/config/LoggerConfig.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,17 @@ package subit.config
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
import kotlinx.serialization.builtins.serializer
import net.mamoe.yamlkt.Comment
import subit.console.ColorDisplayMode
import subit.console.Console
import subit.logger.ForumLogger
import subit.logger.ToFileHandler
import java.util.logging.Level
import java.util.logging.LogRecord
import java.util.regex.Pattern
import kotlin.time.Duration
import kotlin.time.Duration.Companion.days

@Serializable
data class LoggerConfig(
Expand All @@ -25,7 +29,9 @@ data class LoggerConfig(
@Comment("日志的颜色样式, 可选值: RGB, SIMPLE, NONE")
val color: ColorDisplayMode,
@Comment("是否在日志中使用样式(加粗, 斜体, 下划线等)")
val effect: Boolean
val effect: Boolean,
@Comment("日志文件保存时间, 超过该时间的日志会被删除, 格式为ISO8601")
val logFileSaveTime: Duration
)
{
@Transient
Expand All @@ -39,12 +45,13 @@ data class LoggerConfig(

var loggerConfig: LoggerConfig by config(
"logger.yml",
LoggerConfig(listOf(), true, "INFO", false, ColorDisplayMode.RGB, true),
LoggerConfig(listOf(), true, "INFO", false, ColorDisplayMode.RGB, true, 7.days),
{ _, new ->
ForumLogger.globalLogger.logger.setLevel(new.level)
Console.ansiEffectMode =
if (new.effect) subit.console.EffectDisplayMode.ON
else subit.console.EffectDisplayMode.OFF
Console.ansiColorMode = new.color
ToFileHandler.clearOld(new.logFileSaveTime)
}
)
122 changes: 80 additions & 42 deletions src/main/kotlin/subit/logger/ForumLogger.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package subit.logger

import kotlinx.datetime.Clock
import kotlinx.datetime.toKotlinInstant
import me.nullaqua.api.reflect.CallerSensitive
import me.nullaqua.kotlin.reflect.getCallerClass
import me.nullaqua.kotlin.reflect.getCallerClasses
Expand All @@ -15,6 +17,7 @@ import subit.workDir
import java.io.*
import java.text.SimpleDateFormat
import java.util.*
import java.util.logging.Formatter
import java.util.logging.Handler
import java.util.logging.Level
import java.util.logging.LogRecord
Expand All @@ -24,6 +27,7 @@ import java.util.zip.ZipOutputStream
import kotlin.jvm.optionals.getOrDefault
import kotlin.reflect.KClass
import kotlin.reflect.jvm.jvmName
import kotlin.time.Duration

/**
* logger系统
Expand Down Expand Up @@ -157,10 +161,45 @@ object ForumLogger
*/
object ToConsoleHandler: Handler()
{
init
{
this.formatter = object: Formatter()
{
override fun format(record: LogRecord): String
{
val message = formatMessage(record)
val level = record.level
val ansiStyle = if (level.intValue() >= Level.SEVERE.intValue()) SimpleAnsiColor.RED.bright()
else if (level.intValue() >= Level.WARNING.intValue()) SimpleAnsiColor.YELLOW.bright()
else if (level.intValue() >= Level.CONFIG.intValue()) SimpleAnsiColor.BLUE.bright()
else SimpleAnsiColor.GREEN.bright()
val head = if (loggerConfig.showLoggerName) String.format(
"%s[%s]%s[%s]%s[%s]%s",
PURPLE.bright(),
ForumLogger.loggerDateFormat.format(record.millis),
CYAN.bright(),
record.loggerName,
ansiStyle,
level.name,
RESET,
)
else String.format(
"%s[%s]%s[%s]%s",
PURPLE.bright(),
ForumLogger.loggerDateFormat.format(record.millis),
ansiStyle,
level.name,
RESET,
)
return "$head $message $RESET"
}
}
}

override fun publish(record: LogRecord) = safe()
{
if (!loggerConfig.check(record)) return
val messages = mutableListOf(record.message)
val messages = mutableListOf(formatter.format(record))

if (record.thrown != null)
{
Expand Down Expand Up @@ -199,33 +238,8 @@ object ToConsoleHandler: Handler()
}
return
}
val level = record.level
val ansiStyle = if (level.intValue() >= Level.SEVERE.intValue()) SimpleAnsiColor.RED.bright()
else if (level.intValue() >= Level.WARNING.intValue()) SimpleAnsiColor.YELLOW.bright()
else if (level.intValue() >= Level.CONFIG.intValue()) SimpleAnsiColor.BLUE.bright()
else SimpleAnsiColor.GREEN.bright()
val head = if (loggerConfig.showLoggerName) String.format(
"%s[%s]%s[%s]%s[%s]%s",
PURPLE.bright(),
ForumLogger.loggerDateFormat.format(record.millis),
CYAN.bright(),
record.loggerName,
ansiStyle,
level.name,
RESET,
)
else String.format(
"%s[%s]%s[%s]%s",
PURPLE.bright(),
ForumLogger.loggerDateFormat.format(record.millis),
ansiStyle,
level.name,
RESET,
)

messages.forEach { message ->
Console.println("$head $message $RESET")
}

messages.forEach(Console::println)
}

override fun flush() = Unit
Expand Down Expand Up @@ -260,6 +274,26 @@ object ToFileHandler: Handler()
init
{
new()
this.formatter = object: Formatter()
{
override fun format(record: LogRecord): String
{
val message = formatMessage(record)
val level = record.level
val head = if (loggerConfig.showLoggerName) String.format(
"[%s][%s][%s]",
ForumLogger.loggerDateFormat.format(record.millis),
record.loggerName,
level.name
)
else String.format(
"[%s][%s]",
ForumLogger.loggerDateFormat.format(record.millis),
level.name
)
return "$head $message"
}
}
}

/**
Expand Down Expand Up @@ -298,9 +332,24 @@ object ToFileHandler: Handler()
fos.close()
}

fun clearOld(duration: Duration = loggerConfig.logFileSaveTime)
{
val files = logDir.listFiles() ?: return
files.asSequence()
.filter { it.name.endsWith(".zip") }
.map { it to it.name.substringBeforeLast(".zip") }
.map { runCatching { it.first to fileDateFormat.parse(it.second) }.getOrNull() }
.filterNotNull()
.map { it.first to it.second.toInstant().toKotlinInstant() }
.map { it.first to (Clock.System.now() - it.second) }
.filter { it.second > duration }
.map { it.first }
.forEach { it.delete() }
}

private fun check()
{
if ((cnt ushr 10) != 0) new()
if ((cnt ushr 10) > 0) new()
}

private fun append(lines: List<String>) = synchronized(this)
Expand All @@ -316,26 +365,15 @@ object ToFileHandler: Handler()
override fun publish(record: LogRecord) = safe()
{
if (!loggerConfig.check(record)) return
val messages = mutableListOf(record.message)
val messages = mutableListOf(formatter.format(record))

if (record.thrown != null)
{
val str = record.thrown.stackTraceToString()
str.split("\n").forEach { messages.add(it) }
}
val messagesWithOutColor = messages.map { colorMatcher.replace(it, "") }
val head = if (loggerConfig.showLoggerName) String.format(
"[%s][%s][%s]",
ForumLogger.loggerDateFormat.format(record.millis),
record.level.name,
record.loggerName
)
else String.format(
"[%s][%s]",
ForumLogger.loggerDateFormat.format(record.millis),
record.level.name
)
append(messagesWithOutColor.map { "$head $it" })
append(messagesWithOutColor)
}

override fun flush() = Unit
Expand Down

0 comments on commit 67dd967

Please sign in to comment.