Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
@file:OptIn(ExperimentalObjCEnum::class)

package com.hedvig.android.logger

import kotlin.experimental.ExperimentalObjCEnum
import kotlin.native.ObjCEnum

/**
* An enum for log priorities that map to [android.util.Log] priority constants
* without a direct import.
*/
@ObjCEnum
enum class LogPriority {
VERBOSE,
DEBUG,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,17 @@ interface LogcatLogger {
}
}

/**
* Installs [logger] in place of the current one, if any, in one step, so no line is lost or reaches the no-op
* logger in between. For a host that installs a better logger once it can.
*/
fun replace(logger: LogcatLogger) {
synchronized(this) {
installedThrowable = RuntimeException("Previous logger installed here")
this.logger = logger
}
}

/**
* Replaces the current logger (if any) with a no-op logger.
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -1,28 +1,83 @@
@file:OptIn(ExperimentalObjCRefinement::class)

package com.hedvig.android.logger

import kotlin.experimental.ExperimentalObjCRefinement
import kotlin.native.HiddenFromObjC
import platform.Foundation.NSLog

class IosLogcatLogger : LogcatLogger {
/**
* Where the iOS app takes Kotlin's log lines, for example to forward them to its own logger. Implemented in Swift and
* installed with [IosLogcatLogger.Companion.install]. Called on whichever thread logged the line.
*/
interface IosLogSink {
/**
* One line at [priority] from [tag]. A throwable logged with the line is named by its class only, since its message
* can quote what was sent.
*/
fun log(priority: LogPriority, tag: String?, message: String)
}

/** Writes every line at [minimumPriority] or above to [write], and drops the rest without building their message. */
class IosLogcatLogger internal constructor(
private val minimumPriority: LogPriority,
private val write: (priority: LogPriority, tag: String?, message: String) -> Unit,
) : LogcatLogger {
override fun log(priority: LogPriority, throwable: Throwable?, tag: String?, message: () -> String) {
val prefix = when (priority) {
LogPriority.VERBOSE -> "V"
LogPriority.DEBUG -> "D"
LogPriority.INFO -> "I"
LogPriority.WARN -> "W"
LogPriority.ERROR -> "E"
LogPriority.ASSERT -> "A"
}
val tagPart = if (tag != null) "[$tag] " else ""
val messagePart = message()
val throwablePart = if (throwable != null) "\n${throwable.stackTraceToString()}" else ""
NSLog("%s", "$prefix/$tagPart$messagePart$throwablePart")
if (priority < minimumPriority) return
val throwablePart = if (throwable != null) " (${throwable::class.simpleName})" else ""
write(priority, tag, message() + throwablePart)
}

companion object {
/** Installs a logger writing every line, with its stack trace, to `NSLog`, unless a logger is installed. */
fun install() {
if (!LogcatLogger.isInstalled) {
LogcatLogger.install(IosLogcatLogger())
LogcatLogger.install(NSLogLogger)
}
}

/**
* Sends every line at [minimumPriority] or above to [sink], replacing the logger installed before, if any. Call it
* before anything else in Kotlin logs, so no line goes to `NSLog` instead.
*/
fun install(sink: IosLogSink, minimumPriority: LogPriority) {
LogcatLogger.replace(IosLogcatLogger(minimumPriority, sink::log))
}

/**
* Installs a logger writing lines at [minimumPriority] or above to `NSLog`, unless a logger is installed. For Kotlin
* code that must not log into the void when the iOS app installed nothing.
*/
@HiddenFromObjC
fun installFallback(minimumPriority: LogPriority) {
if (!LogcatLogger.isInstalled) {
LogcatLogger.install(
IosLogcatLogger(minimumPriority) { priority, tag, message ->
nsLog(priority, tag, message)
},
)
}
}
}
}

private object NSLogLogger : LogcatLogger {
override fun log(priority: LogPriority, throwable: Throwable?, tag: String?, message: () -> String) {
val throwablePart = if (throwable != null) "\n${throwable.stackTraceToString()}" else ""
nsLog(priority, tag, message() + throwablePart)
}
}

private fun nsLog(priority: LogPriority, tag: String?, message: String) {
val prefix = when (priority) {
LogPriority.VERBOSE -> "V"
LogPriority.DEBUG -> "D"
LogPriority.INFO -> "I"
LogPriority.WARN -> "W"
LogPriority.ERROR -> "E"
LogPriority.ASSERT -> "A"
}
val tagPart = if (tag != null) "[$tag] " else ""
NSLog("%s", "$prefix/$tagPart$message")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package com.hedvig.android.logger

import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue

class IosLogcatLoggerTest {
@AfterTest
fun uninstall() {
LogcatLogger.uninstall()
}

@Test
fun `a WARN minimum drops lower priorities without building their message and keeps WARN and above`() {
val written = mutableListOf<String>()
val built = mutableListOf<LogPriority>()
val logger = IosLogcatLogger(LogPriority.WARN) { priority, tag, message -> written += "$priority $tag $message" }

for (priority in LogPriority.entries) {
logger.log(priority, null, "Tag") {
built += priority
priority.name
}
}

assertEquals(listOf(LogPriority.WARN, LogPriority.ERROR, LogPriority.ASSERT), built)
assertEquals(listOf("WARN Tag WARN", "ERROR Tag ERROR", "ASSERT Tag ASSERT"), written)
}

@Test
fun `a VERBOSE minimum keeps every priority`() {
val written = mutableListOf<LogPriority>()
val logger = IosLogcatLogger(LogPriority.VERBOSE) { priority, _, _ -> written += priority }

for (priority in LogPriority.entries) {
logger.log(priority, null, null) { priority.name }
}

assertEquals(LogPriority.entries.toList(), written.toList())
}

@Test
fun `a throwable reaches the sink as its class name only`() {
val sink = RecordingSink()
IosLogcatLogger.install(sink, LogPriority.VERBOSE)

logcat(LogPriority.ERROR, IllegalStateException("member-sentinel-7a1d"), tag = "Tag") { "Failed" }

assertEquals(listOf("ERROR Tag Failed (IllegalStateException)"), sink.lines)
}

@Test
fun `the sink replaces a logger installed before it without a warning line`() {
IosLogcatLogger.install()
val sink = RecordingSink()

IosLogcatLogger.install(sink, LogPriority.INFO)
logcat(LogPriority.INFO) { "After" }
logcat(LogPriority.DEBUG) { "Dropped" }

assertEquals(listOf("INFO null After"), sink.lines)
}

@Test
fun `the fallback does not replace the sink`() {
val sink = RecordingSink()
IosLogcatLogger.install(sink, LogPriority.VERBOSE)

IosLogcatLogger.installFallback(LogPriority.WARN)
logcat(LogPriority.INFO) { "Still the sink" }

assertEquals(listOf("INFO null Still the sink"), sink.lines)
}

@Test
fun `the fallback installs a logger when there is none`() {
IosLogcatLogger.installFallback(LogPriority.WARN)

assertTrue(LogcatLogger.isInstalled)
}

private class RecordingSink : IosLogSink {
val lines = mutableListOf<String>()

override fun log(priority: LogPriority, tag: String?, message: String) {
lines += "$priority $tag $message"
}
}
}
7 changes: 7 additions & 0 deletions app/network/network-clients/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ kotlin {
implementation(projects.languageCore)
implementation(projects.trackingCore)
}
commonTest.dependencies {
implementation(libs.apollo.testingSupport)
implementation(libs.atomicfu)
implementation(libs.coroutines.test)
implementation(libs.ktor.client.mock)
implementation(projects.coreLocale)
}
androidMain.dependencies {
implementation(libs.datadog.sdk.ktor)
implementation(libs.ktor.client.okhttp)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.hedvig.android.network.clients

/**
* What the network clients log beyond GraphQL operation names, error counts, error types and exception classes.
*
* [logsHttpBodies] logs every HTTP request and response with its body. [logsGraphqlData] adds the GraphQL response
* data to the GraphQL log lines, and the response data and operation variables to the attributes of the RUM error a
* GraphQL error reports. [logsGraphqlErrors]
* adds the GraphQL error messages, the errors with their extensions and the response extensions, and exception
* messages; they can quote what was sent, so they have their own switch.
*/
class NetworkLogPolicy(
val logsHttpBodies: Boolean,
val logsGraphqlData: Boolean,
val logsGraphqlErrors: Boolean,
)
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import com.hedvig.android.core.tracking.ErrorSource
import com.hedvig.android.core.tracking.logError
import com.hedvig.android.logger.LogPriority
import com.hedvig.android.logger.logcat
import com.hedvig.android.network.clients.NetworkLogPolicy
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.onCompletion
Expand All @@ -29,13 +30,13 @@ import kotlinx.coroutines.flow.onEach
*/
internal fun ApolloClient.Builder.addHedvigInterceptors(
platformInterceptors: List<ApolloInterceptor>,
logMemberData: Boolean,
networkLogPolicy: NetworkLogPolicy,
): ApolloClient.Builder = this
.apply { platformInterceptors.forEach(::addInterceptor) }
.addInterceptor(LoggingInterceptor(logMemberData))
.addInterceptor(LoggingInterceptor(networkLogPolicy))

internal class LoggingInterceptor(
private val logMemberData: Boolean,
private val networkLogPolicy: NetworkLogPolicy,
) : ApolloInterceptor {
override fun <D : Data> intercept(
request: ApolloRequest<D>,
Expand All @@ -44,8 +45,11 @@ internal class LoggingInterceptor(
logcat(LogPriority.DEBUG) { "GraphQL request for ${request.operation.name()} START." }
return chain.proceed(request).onEach { response ->
logcat(LogPriority.DEBUG) {
val responseData = if (logMemberData) " Response data: ${response.data}" else ""
"GraphQL request for ${request.operation.name()} EMISSION.$responseData"
if (networkLogPolicy.logsGraphqlData) {
"GraphQL request for ${request.operation.name()} EMISSION. Response data: ${response.data}"
} else {
"GraphQL request for ${request.operation.name()} EMISSION."
}
}
val data = response.data
val errors = response.errors.orEmpty().map { it.toGraphqlError() }
Expand All @@ -54,7 +58,12 @@ internal class LoggingInterceptor(
}
if (response.exception != null && response.exception !is CacheMissException) {
logcat(LogPriority.WARN) {
"GraphQL exception for ${request.operation.name()}: ${response.exception}"
val exception = response.exception!!
if (networkLogPolicy.logsGraphqlErrors) {
"GraphQL exception for ${request.operation.name()}: $exception"
} else {
"GraphQL exception for ${request.operation.name()}: ${exception::class.simpleName}"
}
}
}
}.onCompletion {
Expand All @@ -68,16 +77,23 @@ internal class LoggingInterceptor(
request: ApolloRequest<D>,
response: ApolloResponse<D>,
) {
val errorMessagesJoinedToString = errors.joinToString(", ", "[", "]") { it.message }
val errorMessage = "GraphQL errors for ${request.operation.name()}: $errorMessagesJoinedToString"
val errorMessage = if (networkLogPolicy.logsGraphqlErrors) {
val errorMessagesJoinedToString = errors.joinToString(", ", "[", "]") { it.message }
"GraphQL errors for ${request.operation.name()}: $errorMessagesJoinedToString"
} else {
val errorTypes = errors.map { it.extensions.errorType?.value }
"GraphQL errors for ${request.operation.name()}: ${errors.size} (error types $errorTypes)"
}
val errorAttributes = buildMap {
if (logMemberData) {
if (networkLogPolicy.logsGraphqlData) {
put("data", response.data)
put("variables", request.variablesForLog())
}
put("errors", errors)
if (response.extensions.isNotEmpty()) {
put("extensions", response.extensions.toList().joinToString(", ", "[", "]") { it.toString() })
if (networkLogPolicy.logsGraphqlErrors) {
put("errors", errors)
if (response.extensions.isNotEmpty()) {
put("extensions", response.extensions.toList().joinToString(", ", "[", "]") { it.toString() })
}
}
}
logcat(LogPriority.ERROR) {
Expand All @@ -87,7 +103,7 @@ internal class LoggingInterceptor(
append(errorAttributes)
if (data != null) {
append(" There was data and errors at the same time!")
if (logMemberData) {
if (networkLogPolicy.logsGraphqlData) {
append(" Data:$data")
}
}
Expand Down
Loading
Loading