Hello, is there a way to provide a coroutine name ...
# coroutines
a
Hello, is there a way to provide a coroutine name into log using logback? It works with
-Dkotlinx.coroutines.debug
, but what to do in prod?
s
You can manually set a
CoroutineName
.
a
yes I already do it, but logs looks like 2023-05-04 181807.093 [DefaultDispatcher-worker-1] INFO a.r.b.s.Subscription - Subscribe: SubscribeFlowGraphChangeRequestPayload(flowId=6)
my scope:
Copy code
CoroutineScope(
        Dispatchers.Default +
        CoroutineName("SubscriptionManager")
)
in logback log pattern is
Copy code
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
(I assume that thread name not changed)
y
Not sure how logback works, but what you might wanna do is make a suspending version of the log function and inside access the coroutine name and add it to the log.
s
Ah, IIRC KotlinX debug changes the
Thread.name
which is probably why it works with
[%thread]
🤔
a
Seems so, but without debug, logger grab
DefaultDispatcher-worker-1
, I don't understand why not coroutineName, what disadvantages of it?
s
DefaultDispatcher-worker-1
is set by the
ThreadFactory
, and. logback never interacts with
CoroutineContext
so it doesn't know about
CoroutineName
.
ThreadFactory
is also not aware of the
CoroutineContext
, so it cannot easily do that
a
*I know that threads and coroutines are different
y
Logback isn't aware of coroutines, and coroutines don't automatically set and reset thread name (because you might want the distinction)
a
but how it works with debug? Does it means, that coroutine name just replace thread name by coroutine name and it can be wrong because multiple coroutines can share one thread?
y
It can't ever be wrong because a thread can only run a single coroutine at a time. The debug option causes coroutine dispatcher to automatically set and unset the name because it's reasonable to think that while debugging coroutines you care more about coroutine names
a
Thanks for explaining
m
@Andrey Tabakov Thanks for raising this question. In the Klogging logging library (a Kotlin alternative to Logback) I had used only the thread name as the context for a log event. Some dispatchers appear to include coroutine information in the thread name on switching (e.g. adding
@coroutine#41
) but others do not. I have modified Klogging to read coroutine name from the current context and add it if present. The current snapshot build constructs a context string like
DefaultDispatcher-worker-1+SubscriptionManager
if
SubscriptionManager
is set as the coroutine name. Let me know if this is helpful.
If you try Klogging as a replacement for Logback, please let me know, especially if you need help or new features.
115 Views