object LogUtil {
private var isDebug = BuildConfig.DEBUG
private const val TOP_BORDER =
"╔══════════════════════════════════════════════════════════════════════════════════════════════════════════"
private const val LEFT_BORDER = "║ "
private const val BOTTOM_BORDER =
"╚══════════════════════════════════════════════════════════════════════════════════════════════════════════"
private const val CHUNK_SIZE = 106 //设置字节数
fun d(message: String, tag: String = "SpeedTubeLog") {
if (isDebug) {
val newMsg = msgFormat(message)
Log.d(tag, newMsg)
}
}
fun i(message: String, tag: String = "SpeedTubeLog") {
if (isDebug) {
val newMsg = msgFormat(message)
Log.i(tag, newMsg)
}
}
fun w(message: String, tag: String = "SpeedTubeLog") {
if (isDebug) {
val newMsg = msgFormat(message)
Log.w(tag, newMsg)
}
}
fun e(message: String, tag: String = "SpeedTubeLog") {
if (isDebug) {
val newMsg = msgFormat(message)
Log.e(tag, newMsg)
}
}
private fun msgFormat(msg: String): String {
val bytes: ByteArray = msg.toByteArray()
val length = bytes.size
val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US)
var newMsg =
"$TOP_BORDER\n$LEFT_BORDER\t${sdf.format(Date())}\n$LEFT_BORDER\t${targetStackTraceMSg()}"
if (length > CHUNK_SIZE) {
var i = 0
while (i < length) {
val count = (length - i).coerceAtMost(CHUNK_SIZE)
val tempStr = String(bytes, i, count)
newMsg += "\n$LEFT_BORDER\t$tempStr"
i += CHUNK_SIZE
}
} else {
newMsg += "\n$LEFT_BORDER\t$msg"
}
newMsg += "\n$BOTTOM_BORDER"
return newMsg
}
private fun targetStackTraceMSg(): String {
val targetStackTraceElement = getTargetStackTraceElement()
return if (targetStackTraceElement != null) {
"at ${targetStackTraceElement.className}.${targetStackTraceElement.methodName}(${targetStackTraceElement.fileName}:${targetStackTraceElement.lineNumber})"
} else {
""
}
}
private fun getTargetStackTraceElement(): StackTraceElement? {
var targetStackTrace: StackTraceElement? = null
var shouldTrace = false
val stackTrace = Thread.currentThread().stackTrace
for (stackTraceElement in stackTrace) {
val isLogMethod = stackTraceElement.className == LogUtil::class.java.name
if (shouldTrace && !isLogMethod) {
targetStackTrace = stackTraceElement
break
}
shouldTrace = isLogMethod
}
return targetStackTrace
}
}
╔══════════════════════════════════════════════════════════════════════════════════════════════════════════
║ 2024-01-17 13:05:01
║ at 包名.类名.方法名$lambda$1(类名.kt:133)
║ 打印内容
╚══════════════════════════════════════════════════════════════════════════════════════════════════════════