Skip to content

Commit

Permalink
Refactor LoggingEvent and improve error handling
Browse files Browse the repository at this point in the history
Changed LoggingEvent from a data class to a regular class. Enhanced error handling in Logger and improved test cases for better exception logging. Also added stack trace printing in ConsoleAppender.
  • Loading branch information
smyrgeorge committed Oct 17, 2024
1 parent 27809ff commit b0c890e
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,9 @@ abstract class Logger {
fun debug(msg: String, vararg args: Any?): Unit = log(Level.DEBUG, msg, args)
fun info(msg: String, vararg args: Any?): Unit = log(Level.INFO, msg, args)
fun warn(msg: String, vararg args: Any?): Unit = log(Level.WARN, msg, args)
fun error(msg: String, vararg args: Any?): Unit = log(Level.ERROR, msg, args)
fun error(msg: String, throwable: Throwable, vararg args: Any?): Unit = log(Level.ERROR, msg, throwable, args)
fun error(msg: String?, vararg args: Any?): Unit = log(Level.ERROR, msg ?: "", args)
fun error(msg: String?, throwable: Throwable, vararg args: Any?): Unit =
log(Level.ERROR, msg ?: "", throwable, args)

companion object {
fun of(name: String): Logger = RootLogger.factory.getLogger(name)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ package io.github.smyrgeorge.log4k

import kotlinx.datetime.Instant

@Suppress("ArrayInDataClass")
data class LoggingEvent(
class LoggingEvent(
var id: Long = 0,
val level: Level,
val logger: String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ class ConsoleAppender : Appender {
override val name: String = this::class.toName()
override fun append(event: LoggingEvent) {
print(event.format())
event.throwable?.printStackTrace()
}

private fun LoggingEvent.format(): String {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,19 @@ class MainTests {
log.info("this is a test")
RootLogger.loggers.mute("io.github.smyrgeorge.log4k.MainTests")
log.info("this is a test with 1 arg: {}", "hello")
RootLogger.loggers.unmute("io.github.smyrgeorge.log4k.MainTests")
RootLogger.loggers.unmute(this::class)
log.info("this is a test with 1 arg: {}", "hello")

try {
error("An error occurred!")
} catch (e: Exception) {
log.error(e.message)
log.error(e.message, e)
}

runBlocking {
withContext(Dispatchers.IO) {
delay(1000)
delay(2000)
}
}
}
Expand Down

0 comments on commit b0c890e

Please sign in to comment.