sentry-java icon indicating copy to clipboard operation
sentry-java copied to clipboard

Kotlin Coroutine Support

Open yukukotani opened this issue 6 years ago • 10 comments

When we switch threads via coroutine, all information in hub (e.g. extra and breadcrumbs) are lost because it's thread local.

class MyClass {
    suspend fun example() {
        // Record a breadcrumb in the scope.
        Sentry.addBreadcrumb("On First Thread")
        Sentry.captureMessage("This message captured with breadcrumb 'On First Thread'")
        
        withContext(Dispatchers.IO) {
            Sentry.captureMessage("This message captured without breadcrumb")
            Sentry.addBreadcrumb("On Second Thread")
            Sentry.captureMessage("This message captured with breadcrumb 'On Second Thread'")
        }
    }
}

I think sentry-java should provide something to keep thread local information when switching thread or the implementation of IHub that delegates everything to CorotuineContext.

yukukotani avatar Oct 10 '20 19:10 yukukotani

I've this same problem when using sentry with spring webflux and reactor project (there should be a way to preserve context in another way that is not thread local)

dbuos avatar Oct 11 '20 13:10 dbuos

kotlinx-coroutines-slf4j solves this for the Logging MDC Context. Something like that would be really nice for the Sentry Context. It would be great if a copy of the current sentry context could be transported from one coroutine to another to avoid the context is changed from different threads / child coroutines or may be cleared/closed (https://github.com/getsentry/sentry-java/issues/1226)

I had a simple custom solution for the sentry client 1.7.30, but with 4.x it ist hard to get access to underlaying thread local.

/**
 * Sentry context element for the CoroutineContext
 * @see kotlinx.coroutines.slf4j.MDCContext
 */
class SentryContext : ThreadContextElement<SentryContext.SentryContextData?>, AbstractCoroutineContextElement(Key) {
    /**
     * Key of [SentryContext] in [CoroutineContext].
     */
    companion object Key : CoroutineContext.Key<SentryContext>

    /**
     * The value of [SentryContext] context .
     */
    private val contextData: SentryContextData = SentryContextData.fromContext(Sentry.getContext())

    override fun updateThreadContext(context: CoroutineContext): SentryContextData? {
        val oldState = SentryContextData.fromContext(Sentry.getContext())
        setCurrent(contextData)
        return oldState
    }

    override fun restoreThreadContext(context: CoroutineContext, oldState: SentryContextData?) {
        setCurrent(oldState)
    }

    private fun setCurrent(contextData: SentryContextData?) {
        if (contextData == null) {
            Sentry.getContext().clear()
        } else {
            try {
                val sentryContext = Sentry.getContext()
                sentryContext.user = contextData.user
                sentryContext.http = contextData.http
                contextData.tags?.forEach {
                    sentryContext.addTag(it.key, it.value)
                }
            } catch (ex: Exception) {
                // ignore
            }
        }
    }

    data class SentryContextData(
        val user: User?,
        val http: HttpInterface?,
        val tags: Map<String, String>?
    ) {
        companion object {
            @JvmStatic
            fun fromContext(context: Context) =
                SentryContextData(
                    user = context.user,
                    http = context.http,
                    tags = context.tags
                )
        }
    }
}

usage with example above:

class MyClass {
    suspend fun example() {
        // Record a breadcrumb in the scope.
        Sentry.addBreadcrumb("On First Thread")
        Sentry.captureMessage("This message captured with breadcrumb 'On First Thread'")
        
        withContext(Dispatchers.IO + SentryContext()) { // use SentryContext here
            Sentry.captureMessage("This message captured without breadcrumb")
            Sentry.addBreadcrumb("On Second Thread")
            Sentry.captureMessage("This message captured with breadcrumb 'On Second Thread'")
        }
    }
}

sebastianfuss avatar Mar 01 '21 17:03 sebastianfuss

Seeing the same issue on Spring boot, sentry v4.3.0.

I would hope for this to be higher priority. Had just paid up for sentry, this is a dealbreaker for us :(

amitav13 avatar Apr 27 '21 07:04 amitav13

Something interesting to note: this seems to be happening with kotlin on spring boot only. It's working on android with kotlin as expected.

amitav13 avatar Apr 28 '21 09:04 amitav13

@amitav13 the reason is, the thread-local behavior is deactivated on Android because it's a single user (so single Hub/Scope too).

marandaneto avatar Apr 28 '21 09:04 marandaneto

@amitav13 the reason is, the thread-local behavior is deactivated on Android because it's a single user (so single Hub/Scope too).

Can we configure that? Because we have a destkop application (so, it is a single user too), but we do suffer from this problem.

jcornaz avatar Apr 28 '21 10:04 jcornaz

@jcornaz yes

https://getsentry.github.io/sentry-java/ init the SDK using globalHubMode=true

marandaneto avatar Apr 28 '21 11:04 marandaneto

+1 for this, any similar product out there with this in their SDK? or any suggested integration that could bypass this issue?

kangaroo5383 avatar May 11 '21 18:05 kangaroo5383

@maciejwalkowiak I guess this issue is also related to https://github.com/getsentry/sentry-java/projects/1#card-45749403 so can we archive the card?

marandaneto avatar May 12 '21 11:05 marandaneto

+1 for this, any similar product out there with this in their SDK? or any suggested integration that could bypass this issue?

we're currently figuring this out.

marandaneto avatar May 12 '21 11:05 marandaneto