Skip to content

Instantly share code, notes, and snippets.

@ErikHellman
Last active November 21, 2017 09:31
Show Gist options
  • Save ErikHellman/8efdb102fd361b3cba1eef8bdebf8dcf to your computer and use it in GitHub Desktop.
Save ErikHellman/8efdb102fd361b3cba1eef8bdebf8dcf to your computer and use it in GitHub Desktop.
Twig - A logcat wrapper using Kotlin reified generics
package se.hellsoft.twig
import android.util.Log
import se.hellsoft.kotlinhacks.BuildConfig
/**
* Verbose logging. Will be stripped from release builds.
*/
inline fun <reified T> T.logv(error: Throwable? = null, m: () -> String) {
if (BuildConfig.DEBUG) {
Twig.writeLog(Log.VERBOSE, T::class.java, m(), error)
}
}
/**
* Info logging. Will be stripped from release builds.
*/
inline fun <reified T> T.logi(error: Throwable? = null, m: () -> String) {
if (BuildConfig.DEBUG) {
Twig.writeLog(Log.INFO, T::class.java, m(), error)
}
}
/**
* Debug logging. Will be stripped from release builds.
*/
inline fun <reified T> T.logd(error: Throwable? = null, m: () -> String) {
if (BuildConfig.DEBUG) {
Twig.writeLog(Log.DEBUG, T::class.java, m(), error)
}
}
/**
* Log a warning. Will not be stripped from release builds.
*/
inline fun <reified T> T.logw(error: Throwable? = null, m: () -> String) {
Twig.writeLog(Log.WARN, T::class.java, m(), error)
}
/**
* Log an error. Will not be stripped from release builds.
*/
inline fun <reified T> T.loge(error: Throwable? = null, m: () -> String) {
Twig.writeLog(Log.ERROR, T::class.java, m(), error)
}
/**
* Simple log wrapper for Android projects in Kotlin.
* This wrapper is not designed to be used from Java.
*/
object Twig {
var logger: LogInterceptor? = null
private val logcatLogger = object : LogInterceptor {
override fun onLog(level: Int, tag: String, message: String, error: Throwable?) {
if (error != null) {
when (level) {
Log.VERBOSE -> Log.v(tag, message, error)
Log.DEBUG -> Log.d(tag, message, error)
Log.INFO -> Log.i(tag, message, error)
Log.WARN -> Log.w(tag, message, error)
Log.ERROR -> Log.e(tag, message, error)
}
} else {
when (level) {
Log.VERBOSE -> Log.v(tag, message)
Log.DEBUG -> Log.d(tag, message)
Log.INFO -> Log.i(tag, message)
Log.WARN -> Log.w(tag, message)
Log.ERROR -> Log.e(tag, message)
}
}
}
}
private fun buildTag(clazz: Class<*>): String {
val packageName = clazz.`package`.name
return if (packageName.length > 1) {
clazz.name.substring(packageName.length + 1)
} else {
clazz.name
}
}
fun writeLog(level: Int, clazz: Class<*>, message: String, error: Throwable? = null) {
val tag = buildTag(clazz)
logger?.onLog(level, tag, message, error)
}
interface LogInterceptor {
fun onLog(level: Int, tag: String, message: String, error: Throwable? = null)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment