SubwayTooter-Android-App/app/src/main/java/jp/juggler/util/LogCategory.kt

74 lines
2.4 KiB
Kotlin
Raw Normal View History

2018-12-01 00:02:18 +01:00
package jp.juggler.util
import android.content.res.Resources
2018-08-28 14:56:09 +02:00
import android.util.Log
2021-06-13 05:30:40 +02:00
import androidx.annotation.StringRes
2022-06-04 20:35:07 +02:00
fun Throwable.withCaption(caption: String? = null) =
when {
caption.isNullOrBlank() -> "${javaClass.simpleName} $message"
else -> "$caption :${javaClass.simpleName} $message"
}
fun Throwable.withCaption(resources: Resources, stringId: Int, vararg args: Any) =
"${resources.getString(stringId, *args)}: ${javaClass.simpleName} $message"
// cause 付きの IllegalStateException を投げる
fun errorEx(cause: Throwable, caption: String): Nothing =
throw IllegalStateException(caption, cause)
2021-06-13 05:30:40 +02:00
class LogCategory(val category: String) {
2021-06-13 05:30:40 +02:00
companion object {
private const val TAG = "SubwayTooter"
}
///////////////////////////////
// string
2021-10-27 22:58:19 +02:00
private fun msg(priority: Int, msg: String): Boolean {
Log.println(priority, TAG, "$category/$msg")
2021-06-13 05:30:40 +02:00
return false
}
fun e(msg: String) = msg(Log.ERROR, msg)
fun w(msg: String) = msg(Log.WARN, msg)
fun i(msg: String) = msg(Log.INFO, msg)
fun d(msg: String) = msg(Log.DEBUG, msg)
fun v(msg: String) = msg(Log.VERBOSE, msg)
///////////////////////////////
// Resources.getString()
2022-06-04 20:35:07 +02:00
private fun msg(
priority: Int,
res: Resources,
@StringRes stringId: Int,
args: Array<out Any?>,
) = msg(priority, res.getString(stringId, *args))
2021-06-13 05:30:40 +02:00
fun e(res: Resources, @StringRes stringId: Int, vararg args: Any?) =
2021-06-13 05:30:40 +02:00
msg(Log.ERROR, res, stringId, args)
fun w(res: Resources, @StringRes stringId: Int, vararg args: Any?) =
2021-06-13 05:30:40 +02:00
msg(Log.WARN, res, stringId, args)
fun i(res: Resources, @StringRes stringId: Int, vararg args: Any?) =
2021-06-13 05:30:40 +02:00
msg(Log.INFO, res, stringId, args)
fun d(res: Resources, @StringRes stringId: Int, vararg args: Any?) =
2021-06-13 05:30:40 +02:00
msg(Log.DEBUG, res, stringId, args)
fun v(res: Resources, @StringRes stringId: Int, vararg args: Any?) =
2021-06-13 05:30:40 +02:00
msg(Log.VERBOSE, res, stringId, args)
///////////////////////////////
// stack trace
fun e(ex: Throwable, caption: String?) =
false.also { Log.e(TAG, "$category/${ex.withCaption(caption)}", ex) }
fun w(ex: Throwable, caption: String?) =
false.also { Log.w(TAG, "$category/${ex.withCaption(caption)}", ex) }
2021-06-13 05:30:40 +02:00
}