Skip to content

Commit 70ab153

Browse files
Regroup Realm breadcrumbs to reduce spam
1 parent 54d44dd commit 70ab153

File tree

1 file changed

+51
-10
lines changed

1 file changed

+51
-10
lines changed

app/src/main/java/com/infomaniak/mail/utils/SentryRealmLogger.kt

+51-10
Original file line numberDiff line numberDiff line change
@@ -22,24 +22,65 @@ import io.realm.kotlin.log.RealmLogger
2222
import io.sentry.Breadcrumb
2323
import io.sentry.Sentry
2424
import io.sentry.SentryLevel
25+
import kotlinx.coroutines.CoroutineScope
26+
import kotlinx.coroutines.Dispatchers
27+
import kotlinx.coroutines.launch
28+
import kotlinx.coroutines.sync.Mutex
29+
import kotlinx.coroutines.sync.withLock
2530

2631
class SentryRealmLogger : RealmLogger {
2732

28-
override val level: LogLevel = LogLevel.DEBUG
33+
private val mutex = Mutex()
34+
private val messagesMap = mutableMapOf<Long, MutableList<String>>()
2935

30-
override val tag: String = "Realm"
36+
override val level = LogLevel.DEBUG
37+
38+
override val tag = "Realm"
3139

3240
override fun log(level: LogLevel, throwable: Throwable?, message: String?, vararg args: Any?) {
41+
3342
val throwableMessage = throwable?.message
34-
val breadcrumb = if (throwableMessage == null) {
35-
Breadcrumb().apply {
36-
this.level = SentryLevel.INFO
37-
this.category = tag
38-
this.message = "($tag): $message"
43+
if (throwableMessage != null) {
44+
val breadcrumb = Breadcrumb.error(throwableMessage).apply { category = "exception" }
45+
Sentry.addBreadcrumb(breadcrumb)
46+
return
47+
}
48+
49+
CoroutineScope(Dispatchers.Default).launch {
50+
mutex.withLock {
51+
val now = System.currentTimeMillis() / MAX_DELAY
52+
53+
message?.let {
54+
if (messagesMap[now] == null) {
55+
messagesMap[now] = mutableListOf(it)
56+
} else {
57+
messagesMap[now]?.add(it)
58+
}
59+
}
60+
61+
var shouldContinue = true
62+
while (shouldContinue) {
63+
val key = messagesMap.keys.firstOrNull()
64+
val values = messagesMap[key]
65+
if (key != null && (key < now || values!!.count() > MAX_ZIP)) {
66+
val breadcrumb = Breadcrumb().apply {
67+
this.level = SentryLevel.INFO
68+
this.category = tag
69+
this.message = values?.joinToString(separator = "\n") { it }
70+
}
71+
Sentry.addBreadcrumb(breadcrumb)
72+
messagesMap.remove(key)
73+
74+
} else {
75+
shouldContinue = false
76+
}
77+
}
3978
}
40-
} else {
41-
Breadcrumb.error(throwableMessage).apply { category = "exception" }
4279
}
43-
Sentry.addBreadcrumb(breadcrumb)
80+
}
81+
82+
companion object {
83+
private const val MAX_DELAY = 100
84+
private const val MAX_ZIP = 100
4485
}
4586
}

0 commit comments

Comments
 (0)