Skip to content

Quickly setup properties to be appended onto the MDC per request

Notifications You must be signed in to change notification settings

TelenorNorway/boot3-configurable-mdc

Repository files navigation

boot3-configurable-mdc

A Spring Boot 3 utility library to automatically append those application properties from logging.map.* to your Mapped Diagnostic Context.

Dependency

In your gradle file

Follow this guide on how to set up your environment for GitHub packages.

plugins {
  id("sh.tnn") version "0.2.0"
}

repositories {
  telenor.public()
}

dependencies {
  implementation("no.telenor.kt:boot3-configurable-mdc:<VERSION HERE>")
  // implementation("org.springframework.boot:spring-boot-starter-web")
}

Usage

logging.map:
  request.userAgent: '#request.getHeader("user-agent")'
  request.correlationId: '#request.getHeader("x-correlation-id") ?: T(java.util.UUID).randomUUID()'

Other libraries can also provide default mappers that can either be enabled by default, or manually enabled in configuration:

@Configuration
public class MyDefaultMdcMappers {
  MyDefaultMdcMappers(KeyRegistry registry) {
    // Add request.userAgent, which is enabled by default.
    registry.define(
      "request.userAgent",
      (context) -> ((HttpServletRequest) context.get("request")).getHeader("user-agent")
    );
  }
}

This will now append request.userAgent to the MDC by default, this can be disabled in the application properties by using a falsy boolean on the key:

logging.map:
  request.userAgent: off # false

Similarly, we can create a default key that must be manually enabled in the application properties.

public class MyDefaultMdcMappers {
  MyDefaultMdcMappers(KeyRegistry registry) {
    registry.define(
      "request.id",
      false, // enabled = false | true
      (context) -> Optional.ofNullable(((HttpServletRequest) context.get("request")).getHeader("x-request-id"))
        .orElse(UUID.randomUUID())
    );
  }
}

The above default value will be registered, but it will not be included by default, but can be activated using the application properties.

logging.map:
  request.id: on # true

About

Quickly setup properties to be appended onto the MDC per request

Resources

Stars

Watchers

Forks

Packages