kotlinx.coroutines icon indicating copy to clipboard operation
kotlinx.coroutines copied to clipboard

make CoroutineId public

Open caplan opened this issue 3 years ago • 10 comments

A coroutine object's toString() debug output is sometimes a bit too much info. It would be useful to be able to access more fine-grained coroutine info for the sake of logging/debugging. We already have access to kotlinx.coroutines.CoroutineName, but kotlinx.coroutines.CoroutineId is internal. Could it be public?

caplan avatar Mar 21 '21 17:03 caplan

It is definitely possible. Could you please elaborate on why one may want to use CoroutineId programattically?

qwwdfsad avatar Mar 22 '21 15:03 qwwdfsad

We'd like to log essentially a stack/tree of coroutine lifecycles, e.g.

foo#264 created from bar#453
baz#13 created from foo#264
baz#14 created from foo#264
baz#14 ended
baz#13 ended
foo#264 ended

We therefore need unique strings to log for each coroutine.

caplan avatar Mar 22 '21 15:03 caplan

alternatively, making CoroutineContext.coroutineName public would be sufficient for our current use case.

caplan avatar Mar 22 '21 15:03 caplan

Would you accept a pr that makes CoroutineContext.coroutineName public (and adds docs)?

caplan avatar Jun 28 '21 15:06 caplan

But CoroutineName is already public, could you please elaborate on why coroutineContext[CoroutineName] is not sufficient?

qwwdfsad avatar Jun 28 '21 16:06 qwwdfsad

CoroutineName does not include the sequence number unfortunately

caplan avatar Jun 28 '21 16:06 caplan

I see. The problem here is that coroutineName is not consistent with already public CoroutineName. I'm aiming to fix it in 1.6.0 along with the rest of our debugging and diagnostic issues, so stay tuned and thanks for the reminder of this issue!

qwwdfsad avatar Jun 28 '21 18:06 qwwdfsad

At least, make public for CoroutineContext.coroutineName property please

In my case, I use Redisson Lock. redisson lock basically used under Current Thread Id. When I use Redisson Lock in Coroutines, Current Thread is changed, So Need to pass to lock/unlock with some id

currently I use like this

val CoroutineScope.currentCoroutineId: Long
    get() = this.coroutineContext.toString().hashCode().toLong()
    
 lock.lockAsync(2, SECONDS, currentCoroutineId).awaitSuspending()
 delay(100)
 lock.unlockAsync(currentCoroutineId).awaitSuspending()    

debop avatar Apr 17 '22 08:04 debop

debop In my case, I use Redisson Lock. redisson lock basically used under Current Thread Id. When I use Redisson Lock in Coroutines, Current Thread is changed, So Need to pass to lock/unlock with some id

I highly not recommend using CoroutineId for this. To understand why, and for a better solution, please read https://elizarov.medium.com/phantom-of-the-coroutine-afc63b03a131

elizarov avatar Apr 18 '22 12:04 elizarov

@elizarov Thanks a lot for idea

debop avatar Apr 21 '22 15:04 debop