AAkira / Napier

Logging library for Kotlin Multiplatform
Apache License 2.0
786 stars 34 forks source link

Logging from another thread on iOS #56

Closed soniccat closed 3 years ago

soniccat commented 3 years ago

Hi. I've tried to call Napier.v on iOS inside of withContext(Dispatchers.Default) i.e. from a non-main thread and didn't get anything logged. I see you use ThreadLocal annotation for Napier. And it seems on iOS I need to initialize Napier separately for Dispatchers.Default thread. Probably it worth adding support for logging from a non-main thread by default as now it looks like a bug.

In this example, I see only the first message logged on iOS. But the both messages are logged on Android. If I add Napier initialization inside of Dispatchers.Default, the both messages will be logged on iOS too:

suspend fun loadDefinition(word: String): OwlBotWord {
        Napier.v("Loading definition for: $word", tag = TAG)

        val res: HttpResponse = httpClient.get("${baseUrl}api/v4/dictionary/${word}")
        return withContext(Dispatchers.Default) {
            // If I initialize Napper here the second message will be logged
            val response = res.readBytes().decodeToString()
            if (res.status == HttpStatusCode.OK) {
                Napier.v("Loded definition for: $word", tag = TAG)
            } else {
                Napier.e("Status: ${res.status} response: $response", tag = TAG)
            }
            Json {
                ignoreUnknownKeys = true
            }.decodeFromString(response)
        }
    }

For now I've ended up with calling this on iOS in a setup function:

    private val defaultScope = CoroutineScope(Dispatchers.Default + SupervisorJob())

    actual fun setupDebug() {
        Napier.base(DebugAntilog())

        defaultScope.launch {
            Napier.base(DebugAntilog())
        }
    }
RomeuG commented 3 years ago

Any news on this?

PhilipDukhov commented 3 years ago

@RomeuG you can check out my solution. Not sure if the maintainer is available.

RomeuG commented 3 years ago

Thanks, I guess Napier itself is dead.

SorrowBlue commented 3 years ago

@RomeuG @PhilipDukhov I contacted the maintainer on Twitter. He has plans to respond after May. Because he is busy now.

AAkira commented 3 years ago

Please check 2.0.0-alpha2