Skip to content

Commit 4e2dc5f

Browse files
committed
Adapt log format
1 parent 52eb732 commit 4e2dc5f

1 file changed

Lines changed: 27 additions & 5 deletions

File tree

LogcatCoreLib/src/main/java/info/hannes/timber/DebugFormatTree.kt

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,38 @@ package info.hannes.timber
33
import org.json.JSONException
44
import org.json.JSONObject
55
import timber.log.Timber
6+
import timber.log.Timber.Forest.tag
67

7-
open class DebugFormatTree : Timber.DebugTree() {
8+
/* If you use old logcat, e.g Android Studio Electric Eel, you should use for newLogcat a false */
9+
open class DebugFormatTree(private val newLogcat: Boolean = true) : Timber.DebugTree() {
10+
11+
private var codeIdentifier = ""
12+
private var method = ""
813

914
override fun createStackElementTag(element: StackTraceElement): String? {
10-
return String.format(
15+
if (newLogcat) {
16+
method = String.format(
17+
"%s.%s()",
18+
// method is fully qualified only when class differs on filename otherwise it can be cropped on long lambda expressions
19+
super.createStackElementTag(element)?.replaceFirst(element.fileName.takeWhile { it != '.' }, ""),
20+
element.methodName
21+
)
22+
23+
codeIdentifier = String.format(
24+
"(%s:%d)",
25+
element.fileName,
26+
element.lineNumber // format ensures line numbers have at least 3 places to align consecutive output from the same file
27+
)
28+
return "(${element.fileName}:${element.lineNumber})"
29+
} else
30+
return String.format(
1131
"(%s:%d) %s.%s()",
1232
element.fileName,
1333
element.lineNumber, // format ensures line numbers have at least 3 places to align consecutive output from the same file
1434
// method is fully qualified only when class differs on filename otherwise it can be cropped on long lambda expressions
1535
super.createStackElementTag(element)?.replaceFirst(element.fileName.takeWhile { it != '.' }, ""),
1636
element.methodName
17-
)
37+
)
1838
}
1939

2040
// if there is an JSON string, try to print out pretty
@@ -24,9 +44,11 @@ open class DebugFormatTree : Timber.DebugTree() {
2444
try {
2545
val json = JSONObject(message)
2646
localMessage = json.toString(3)
27-
} catch (e: JSONException) {
47+
} catch (_: JSONException) {
2848
}
2949
}
30-
super.log(priority, tag, localMessage, t)
50+
if (newLogcat)
51+
localMessage = codeIdentifier + localMessage
52+
super.log(priority, tag, "$method: $localMessage", t)
3153
}
3254
}

0 commit comments

Comments
 (0)