oshai/kotlin-logging

Improving Log Analytics by Indexing Cause Messages

matiasvigil opened this issue · 1 comments

The cause message in logs is often crucial for understanding what went wrong. However, since it is not indexed, filtering and running analytics on it can be challenging. To address this, the cause message can be added to the log's MDC (Mapped Diagnostic Context) by default. This will make it available as any other MDC field, enabling easier filtering.

Current code

internal class JulLoggerWrapper(override val underlyingLogger: Logger) :
  KLogger, DelegatingKLogger<Logger> {
  override val name: String
    get() = underlyingLogger.name

  override fun at(
    level: io.github.oshai.kotlinlogging.Level,
    marker: Marker?, // marker is not supported in JUL
    block: KLoggingEventBuilder.() -> Unit,
  ) {
    if (isLoggingEnabledFor(level, null)) {
      KLoggingEventBuilder().apply(block).run {
        underlyingLogger.log(level.toJULLevel(), message, cause)
      }
    }
  }

Proposed change

By adding the cause message to the MDC, we can enhance log analytics capabilities. The proposed change is as follows:

internal class JulLoggerWrapper(override val underlyingLogger: Logger) :
  KLogger, DelegatingKLogger<Logger> {
  override val name: String
    get() = underlyingLogger.name

  override fun at(
    level: io.github.oshai.kotlinlogging.Level,
    marker: Marker?, // marker is not supported in JUL
    block: KLoggingEventBuilder.() -> Unit,
  ) {
    if (isLoggingEnabledFor(level, null)) {
      KLoggingEventBuilder().apply(block).run {
        withLoggingContext("causeMessage" to cause?.message) {
          underlyingLogger.log(level.toJULLevel(), message, cause)
        }
      }
    }
  }

Additional Considerations

This change is an example and might need to be applied to other similar logging functions or classes within the codebase to ensure consistency and full coverage. Ensure to review and update all relevant logging points.

Thank you for reporting an issue. See the wiki for documentation and slack for questions.