-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLog.kt
86 lines (74 loc) · 2.68 KB
/
Log.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
* Provides an effective mechanism for handling logs.
*
* @author Alexander Khrapunsky
* @version 1.0.1, 29/06/2021.
* @since 1.0.0
*/
object Log {
const val TAG = "ads" // TODO change default tag for logging
var DEBUG = true // TODO disable in release
private val lockHeader = ReentrantLock(true)
fun getHeader(): String {
if (!lockHeader.tryLock(50, TimeUnit.MILLISECONDS)) {
return "[]: "
}
try {
val currentClassName = Log.javaClass.name
val traces = Thread.currentThread().stackTrace
var found = false
for (trace in traces) {
try {
if (found) {
if (!trace.className.startsWith(currentClassName)) {
val targetClassName = Class.forName(trace.className)
return "[${getClassName(targetClassName)}.${trace.methodName}.${trace.lineNumber}]: "
}
}
else if (trace.className.startsWith(currentClassName)) {
found = true
continue
}
} catch (e: ClassNotFoundException) {
} catch (e2: IncompatibleClassChangeError) {
}
}
} catch (eThread: InterruptedException) {
e(eThread)
} finally {
lockHeader.unlock()
}
return "[]: "
}
private fun getClassName(clazz: Class<*>?): String {
if (clazz != null) {
if (!clazz.simpleName.isNullOrEmpty()) {
return clazz.simpleName
} else {
return getClassName(clazz.enclosingClass)
}
} else {
return ""
}
}
inline fun d(tag: String = TAG, msg: () -> String) {
if (DEBUG) android.util.Log.d(tag, getHeader() + msg())
}
inline fun i(tag: String = TAG, msg: () -> String) {
if (DEBUG) android.util.Log.i(tag, getHeader() + msg())
}
inline fun v(tag: String = TAG, msg: () -> String) {
if (DEBUG) android.util.Log.v(tag, getHeader() + msg())
}
inline fun w(tag: String = TAG, msg: () -> String) {
if (DEBUG) android.util.Log.w(tag, getHeader() + msg())
}
inline fun e(tag: String = TAG, cause: Throwable, noinline msg: (() -> String)? = null) {
if (DEBUG) {
android.util.Log.e(tag, msg?.let { it.invoke() } ?: "", cause)
}
}
inline fun e(cause: Throwable) {
if (DEBUG) android.util.Log.e(TAG, "", cause)
}
}