0

I want to modify this log helper function to print out coroutine id or name.

   @JvmInline
   value class MyLogger(private val tag: String) {       
    fun log(level: Level, e: Throwable? = null, message: String) {
    if (isLoggingEnabled(level)) {
        val logTime = System.currentTimeMillis()
        val messageWithCoroutineInfo = "Running on: [${Thread.currentThread().name}] | $message"
        when (level) {
            Level.VERBOSE -> Log.v(tag, messageWithCoroutineInfo, e)
            Level.DEBUG -> Log.d(tag, messageWithCoroutineInfo, e)
            Level.INFO -> Log.i(tag, messageWithCoroutineInfo, e)
            Level.WARN -> Log.w(tag, messageWithCoroutineInfo, e)
            Level.ERROR -> Log.e(tag, messageWithCoroutineInfo, e)
            Level.ASSERT -> Log.wtf(tag, messageWithCoroutineInfo, e)
        }
    }
}
 ....
}


private val logger = MYLogger("Navigator")
logger.i { "goTo: $screen; backstack: [${backStack.joinToString()}]" }

In onCreate function:

    override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)
    System.setProperty("kotlinx.coroutines.debug", if(!BuildTypes.isProduction) "on" else "off")

it can print out the thread name, but it can't print out the coroutine id or name, such as [AWT-EventQueue-0 @coroutine#40], any suggestion?

1

1 Answer 1

0

The information you are looking for is likely in the current coroutine context, which you can get from currentCoroutineContext() inside any suspending function. For example

fun main() {
    val deferred = CoroutineScope(Dispatchers.Default)
        .async {
            println("Coroutine context : ${currentCoroutineContext()}")
        }
    runBlocking { deferred.await() }
}

will print off

Coroutine context : [DeferredCoroutine{Active}@76ff1b25, Dispatchers.Default]

The currentCoroutineContext function is only available inside a suspending function, though, so this would require a modification of how your logger works currently.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.