getLoggingContext

Returns a copy of the log fields in the current thread's logging context (from withLoggingContext). This can be used to pass logging context between threads (see example below).

If you spawn threads using a java.util.concurrent.ExecutorService, you may instead use the dev.hermannm.devlog.inheritLoggingContext extension function, which does the logging context copying from parent to child for you.

Example

Scenario: We store an updated order in a database, and then want to asynchronously update statistics for the order.

import dev.hermannm.devlog.field
import dev.hermannm.devlog.getLogger
import dev.hermannm.devlog.getLoggingContext
import dev.hermannm.devlog.withLoggingContext
import kotlin.concurrent.thread

private val log = getLogger()

class OrderService(
private val orderRepository: OrderRepository,
private val statisticsService: StatisticsService,
) {
fun updateOrder(order: Order) {
withLoggingContext(field("order", order)) {
orderRepository.update(order)
updateStatistics(order)
}
}

// In this scenario, we don't want updateStatistics to block updateOrder, so we spawn a thread.
//
// But we want to log if it fails, and include the logging context from the parent thread.
// This is where getLoggingContext comes in.
private fun updateStatistics(order: Order) {
// We call getLoggingContext here, to copy the context fields from the parent thread
val loggingContext = getLoggingContext()

thread {
// We then pass the parent context to withLoggingContext here in the child thread
withLoggingContext(loggingContext) {
try {
statisticsService.orderUpdated(order)
} catch (e: Exception) {
// This log will get the "order" field from the parent logging context
log.error(e) { "Failed to update order statistics" }
}
}
}
}
}