Skip to content

Instantly share code, notes, and snippets.

@ConorGarry
Last active October 25, 2023 09:56
Show Gist options
  • Save ConorGarry/2e081c59c74ac56cc2dcc2471e805529 to your computer and use it in GitHub Desktop.
Save ConorGarry/2e081c59c74ac56cc2dcc2471e805529 to your computer and use it in GitHub Desktop.
Implementation of kermit-core multiplatform logger. Adds clickable line number, and uses calling file name as tag if none is provided.
import co.touchlab.kermit.BaseLogger
import co.touchlab.kermit.LoggerConfig
import co.touchlab.kermit.Severity
import co.touchlab.kermit.mutableLoggerConfigInit
import co.touchlab.kermit.platformLogWriter
@Suppress("ClassName") // lower case class name.
open class log(
config: LoggerConfig,
) : BaseLogger(config) {
// TODO: Log limit depending on build variant/type?
companion object : log(
mutableLoggerConfigInit(listOf(platformLogWriter()))
)
private fun log(
severity: Severity,
tag: String?,
message: String,
throwable: Throwable? = null
) {
// Get calling File and line number from stacktrace.
val trace = with(Thread.currentThread().stackTrace) {
this[indexOfLast { it.fileName == "Logging.kt" } + 1] // +1 will always be calling class.
}
val file = trace?.fileName.orEmpty()
val line = trace?.lineNumber ?: -1
logBlock(severity, tag ?: file, throwable) { "($file:$line) $message" }
}
// Verbose
fun v(message: String, tag: String? = null) {
log(Severity.Verbose, tag, message)
}
fun v(tag: String? = null, message: () -> String) {
i(message(), tag)
}
// Debug
fun d(message: String, tag: String? = null) {
log(Severity.Debug, tag, message)
}
fun d(tag: String? = null, message: () -> String) {
d(message(), tag)
}
// Info
fun i(message: String, tag: String? = null) {
log(Severity.Info, tag, message)
}
fun i(tag: String? = null, message: () -> String) {
i(message(), tag)
}
// Warn
fun w(message: String, throwable: Throwable? = null, tag: String? = null) {
log(Severity.Warn, tag, message, throwable)
}
fun w(tag: String? = null, message: () -> String) {
w(message(), tag = tag)
}
fun w(throwable: Throwable? = null, tag: String? = null, message: () -> String) {
w(message(), throwable, tag)
}
// Error
fun e(message: String, throwable: Throwable? = null, tag: String? = null) {
log(Severity.Error, tag, message, throwable)
}
fun e(tag: String? = null, message: () -> String) {
e(message(), tag = tag)
}
fun e(throwable: Throwable? = null, tag: String? = null, message: () -> String) {
e(message(), throwable, tag)
}
// Assert (See Log.wtf in docs).
fun a(message: String, throwable: Throwable? = null, tag: String? = null) {
log(Severity.Assert, tag, message, throwable)
}
fun a(tag: String? = null, message: () -> String) {
e(message(), tag = tag)
}
fun a(throwable: Throwable? = null, tag: String? = null, message: () -> String) {
e(message(), throwable, tag)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment