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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## Unreleased

### Features

- Add a Micrometer metrics integration with opt-in Spring Boot support ([#6116](https://github.com/getsentry/sentry-java/pull/6116))

## 8.56.0

### Fixes
Expand Down
31 changes: 31 additions & 0 deletions sentry-micrometer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,37 @@ SentryMeterRegistry sentryRegistry = new SentryMeterRegistry();
Metrics.addRegistry(sentryRegistry);
```

### Spring Boot

Spring Boot 2, 3, and 4 applications can use auto-configuration by adding `sentry-micrometer`
alongside the matching Sentry Spring Boot starter. The starter does not install this module
transitively.

```kotlin
dependencies {
implementation("io.sentry:sentry-spring-boot-4-starter:<version>")
// Spring Boot 3: implementation("io.sentry:sentry-spring-boot-starter-jakarta:<version>")
// Spring Boot 2: implementation("io.sentry:sentry-spring-boot-starter:<version>")

implementation("io.sentry:sentry-micrometer:<version>")
}
```

Enable the integration explicitly and optionally configure passive polling:

```properties
sentry.micrometer.enabled=true
sentry.micrometer.poll-interval-millis=60000
```

Auto-configuration requires Sentry to be initialized and backs off when the application provides
its own `SentryMeterRegistry` bean. Spring Boot adds the registry to its primary composite registry,
applies compatible `MeterRegistryCustomizer` beans, and closes it with the application context.
Supported metrics registered automatically by Spring Boot Actuator鈥攊ncluding HTTP server, JVM,
process, and logging metrics鈥攁re forwarded through the same registry. Set the polling interval to
zero to keep immediate forwarding enabled without a polling worker; passive auto-generated meters
then remain registered but are not sent.

## Metric mappings

Active meters are forwarded when they are recorded:
Expand Down
1 change: 1 addition & 0 deletions sentry-micrometer/api/sentry-micrometer.api
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ public final class io/sentry/micrometer/BuildConfig {
public final class io/sentry/micrometer/SentryMeterRegistry : io/micrometer/core/instrument/MeterRegistry {
public fun <init> ()V
public fun <init> (J)V
public fun <init> (Lio/sentry/IScopes;J)V
public fun close ()V
}

Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,14 @@
import io.micrometer.core.instrument.internal.DefaultLongTaskTimer;
import io.micrometer.core.instrument.internal.DefaultMeter;
import io.micrometer.core.instrument.util.NamedThreadFactory;
import io.sentry.Sentry;
import io.sentry.IScopes;
import io.sentry.ScopesAdapter;
import io.sentry.SentryAttributes;
import io.sentry.SentryIntegrationPackageStorage;
import io.sentry.SentryLevel;
import io.sentry.metrics.MetricsUnit;
import io.sentry.util.ExceptionUtils;
import io.sentry.util.Objects;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
Expand All @@ -44,6 +46,7 @@ public final class SentryMeterRegistry extends MeterRegistry {
private static final @NotNull String INTEGRATION_NAME = "Micrometer";
private static final long DEFAULT_POLL_INTERVAL_MILLIS = 60_000;

private final @NotNull IScopes scopes;
private final @Nullable ScheduledExecutorService scheduler;
private final @Nullable ScheduledFuture<?> pollingTask;

Expand All @@ -63,14 +66,25 @@ public SentryMeterRegistry() {
* <p>A zero interval disables passive meter polling. Negative intervals are not supported.
*/
public SentryMeterRegistry(final long pollIntervalMillis) {
this(pollIntervalMillis, Clock.SYSTEM, createScheduler(pollIntervalMillis));
this(ScopesAdapter.getInstance(), pollIntervalMillis);
}

/**
* Creates a registry with the given scopes and passive meter polling interval in milliseconds.
*
* <p>A zero interval disables passive meter polling. Negative intervals are not supported.
*/
public SentryMeterRegistry(final @NotNull IScopes scopes, final long pollIntervalMillis) {
this(scopes, pollIntervalMillis, Clock.SYSTEM, createScheduler(pollIntervalMillis));
}

SentryMeterRegistry(
final @NotNull IScopes scopes,
final long pollIntervalMillis,
final @NotNull Clock clock,
final @Nullable ScheduledExecutorService scheduler) {
super(clock);
this.scopes = Objects.requireNonNull(scopes, "Scopes are required");
validatePollInterval(pollIntervalMillis);
if (pollIntervalMillis > 0 && scheduler == null) {
throw new IllegalArgumentException(
Expand Down Expand Up @@ -165,7 +179,7 @@ public SentryMeterRegistry(final long pollIntervalMillis) {
final @NotNull Meter.Id id,
final @NotNull Meter.Type type,
final @NotNull Iterable<Measurement> measurements) {
Sentry.getCurrentScopes()
scopes
.getOptions()
.getLogger()
.log(
Expand All @@ -189,7 +203,7 @@ void captureCounter(final @NotNull SentryMetricInfo metricInfo, final double val
if (isClosed()) {
return;
}
Sentry.getCurrentScopes()
scopes
.metrics()
.count(metricInfo.getName(), value, metricInfo.getUnit(), metricInfo.createParameters());
}
Expand All @@ -198,7 +212,7 @@ void captureDistribution(final @NotNull SentryMetricInfo metricInfo, final doubl
if (isClosed()) {
return;
}
Sentry.getCurrentScopes()
scopes
.metrics()
.distribution(
metricInfo.getName(), value, metricInfo.getUnit(), metricInfo.createParameters());
Expand All @@ -208,7 +222,7 @@ void captureGauge(final @NotNull SentryMetricInfo metricInfo, final double value
if (isClosed()) {
return;
}
Sentry.getCurrentScopes()
scopes
.metrics()
.gauge(metricInfo.getName(), value, metricInfo.getUnit(), metricInfo.createParameters());
}
Expand All @@ -231,7 +245,7 @@ void pollMeters() {
}

void logPollingFailure(final @NotNull Throwable throwable, final @NotNull String meterName) {
Sentry.getCurrentScopes()
scopes
.getOptions()
.getLogger()
.log(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import com.google.common.truth.Truth.assertThat
import io.micrometer.core.instrument.Clock
import io.micrometer.core.instrument.FunctionTimer
import io.sentry.IScopes
import io.sentry.ScopesAdapter
import io.sentry.Sentry
import io.sentry.SentryOptions
import io.sentry.metrics.IMetricsApi
Expand Down Expand Up @@ -357,7 +358,8 @@ class SentryFunctionTimerTest {
val scheduler = mock<ScheduledExecutorService>()
val task = mock<ScheduledFuture<Unit>>()
whenever(scheduler.scheduleAtFixedRate(any(), any(), any(), any())).thenReturn(task)
return SentryMeterRegistry(60_000, Clock.SYSTEM, scheduler).also(registries::add)
return SentryMeterRegistry(ScopesAdapter.getInstance(), 60_000, Clock.SYSTEM, scheduler)
.also(registries::add)
}

private fun installMetricsApi(): IMetricsApi {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import io.micrometer.core.instrument.LongTaskTimer
import io.micrometer.core.instrument.MockClock
import io.micrometer.core.instrument.TimeGauge
import io.sentry.IScopes
import io.sentry.ScopesAdapter
import io.sentry.Sentry
import io.sentry.SentryOptions
import io.sentry.metrics.IMetricsApi
Expand Down Expand Up @@ -66,7 +67,8 @@ class SentryMeterRegistryPollingTest {
)
.thenReturn(task)

val registry = track(SentryMeterRegistry(2500, Clock.SYSTEM, scheduler))
val registry =
track(SentryMeterRegistry(ScopesAdapter.getInstance(), 2500, Clock.SYSTEM, scheduler))
val value = AtomicReference(4.5)
Gauge.builder("scheduled", value) { it.get() }.strongReference(true).register(registry)
val scheduledPoll = argumentCaptor<Runnable>()
Expand Down Expand Up @@ -107,7 +109,7 @@ class SentryMeterRegistryPollingTest {
@Test
fun `zero interval ignores an available scheduler`() {
val scheduler = mock<ScheduledExecutorService>()
track(SentryMeterRegistry(0, Clock.SYSTEM, scheduler))
track(SentryMeterRegistry(ScopesAdapter.getInstance(), 0, Clock.SYSTEM, scheduler))

verifyNoInteractions(scheduler)
}
Expand Down Expand Up @@ -406,7 +408,7 @@ class SentryMeterRegistryPollingTest {
val scheduler = mock<ScheduledExecutorService>()
val task = mock<ScheduledFuture<Unit>>()
whenever(scheduler.scheduleAtFixedRate(any(), any(), any(), any())).thenReturn(task)
return track(SentryMeterRegistry(60_000, clock, scheduler))
return track(SentryMeterRegistry(ScopesAdapter.getInstance(), 60_000, clock, scheduler))
}

private fun track(registry: SentryMeterRegistry): SentryMeterRegistry {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package io.sentry.micrometer
import com.google.common.truth.Truth.assertThat
import io.micrometer.core.instrument.Counter
import io.micrometer.core.instrument.DistributionSummary
import io.micrometer.core.instrument.Gauge
import io.micrometer.core.instrument.Measurement
import io.micrometer.core.instrument.Meter
import io.micrometer.core.instrument.Statistic
Expand All @@ -12,10 +13,12 @@ import io.micrometer.core.instrument.config.MeterFilter
import io.micrometer.core.instrument.config.NamingConvention
import io.micrometer.core.instrument.simple.SimpleMeterRegistry
import io.sentry.Hint
import io.sentry.ILogger
import io.sentry.IScopes
import io.sentry.ISentryClient
import io.sentry.Sentry
import io.sentry.SentryIntegrationPackageStorage
import io.sentry.SentryLevel
import io.sentry.SentryMetricsEvent
import io.sentry.SentryOptions
import io.sentry.metrics.IMetricsApi
Expand Down Expand Up @@ -166,6 +169,58 @@ class SentryMeterRegistryTest {
verify(second).count(eq("counter"), eq(2.0), anyOrNull(), any())
}

@Test
fun `injected scopes receive active and passive metrics instead of global scopes`() {
val globalMetrics = installMetricsApi()
val metrics = mock<IMetricsApi>()
val scopes = mock<IScopes>()
whenever(scopes.metrics()).thenReturn(metrics)
val registry = SentryMeterRegistry(scopes, 0).also(registries::add)

registry.counter("counter").increment(2.0)
registry.timer("timer").record(3, TimeUnit.MILLISECONDS)
registry.summary("summary").record(4.0)
Gauge.builder("gauge", Supplier { 5.0 }).register(registry)
registry.pollMeters()

verify(metrics).count(eq("counter"), eq(2.0), anyOrNull(), any())
verify(metrics).distribution(eq("timer"), eq(3.0), eq(MetricsUnit.Duration.MILLISECOND), any())
verify(metrics).distribution(eq("summary"), eq(4.0), anyOrNull(), any())
verify(metrics).gauge(eq("gauge"), eq(5.0), anyOrNull(), any())
verifyNoInteractions(globalMetrics)
}

@Test
fun `diagnostic logging uses injected scopes`() {
val logger = mock<ILogger>()
val options =
SentryOptions().apply {
isDebug = true
setLogger(logger)
}
val scopes = mock<IScopes>()
whenever(scopes.options).thenReturn(options)
val registry = SentryMeterRegistry(scopes, 0).also(registries::add)
val failure = IllegalStateException("poll failed")

Meter.builder(
"custom",
Meter.Type.OTHER,
listOf(Measurement(Supplier { 7.0 }, Statistic.VALUE)),
)
.register(registry)
registry.logPollingFailure(failure, "gauge")

verify(logger)
.log(
SentryLevel.DEBUG,
"Micrometer meter type %s is not supported for Sentry export.",
Meter.Type.OTHER,
)
verify(logger)
.log(SentryLevel.DEBUG, failure, "Failed to publish Micrometer meter %s to Sentry.", "gauge")
}

@Test
fun `registry created before Sentry init forwards after initialization`() {
Sentry.close()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ dependencies {
implementation(Config.Libs.kotlinReflect)
implementation(kotlin(Config.kotlinStdLib, KotlinCompilerVersion.VERSION))
implementation(projects.sentrySpringBoot4Starter)
implementation(projects.sentryMicrometer)
implementation(projects.sentryLogback)
implementation(projects.sentryGraphql22)
implementation(projects.sentryQuartz)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package io.sentry.samples.spring.boot4;

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import io.sentry.Sentry;
import io.sentry.metrics.MetricsUnit;
import org.slf4j.Logger;
Expand All @@ -14,6 +16,14 @@
public class MetricController {
private static final Logger LOGGER = LoggerFactory.getLogger(MetricController.class);

private final MeterRegistry meterRegistry;
private final SimpleMeterRegistry simpleMeterRegistry;

public MetricController(MeterRegistry meterRegistry, SimpleMeterRegistry simpleMeterRegistry) {
this.meterRegistry = meterRegistry;
this.simpleMeterRegistry = simpleMeterRegistry;
}

@GetMapping("count")
String count() {
Sentry.setAttribute("user.type", "admin");
Expand All @@ -22,6 +32,14 @@ String count() {
return "count metric increased";
}

@GetMapping("micrometer")
String micrometer() {
meterRegistry.counter("micrometer.counter", "source", "spring").increment();
double simpleRegistryCount =
simpleMeterRegistry.get("micrometer.counter").tag("source", "spring").counter().count();
return "micrometer metric increased: " + simpleRegistryCount;
}

@GetMapping("gauge/{value}")
String gauge(@PathVariable("value") Long value) {
Sentry.metrics().gauge("memory.free", value.doubleValue(), MetricsUnit.Information.BYTE);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import static io.sentry.quartz.SentryJobListener.SENTRY_SLUG_KEY;

import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import io.sentry.samples.spring.boot4.quartz.SampleJob;
import java.util.Collections;
import org.quartz.JobDetail;
Expand Down Expand Up @@ -42,6 +43,11 @@ RestClient restClient(RestClient.Builder builder) {
return builder.build();
}

@Bean
SimpleMeterRegistry simpleMeterRegistry() {
return new SimpleMeterRegistry();
}

@Bean
public JobDetailFactoryBean jobDetail() {
JobDetailFactoryBean jobDetailFactory = new JobDetailFactoryBean();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ sentry.enable-spotlight=true
sentry.enablePrettySerializationOutput=false
sentry.in-app-includes="io.sentry.samples"
sentry.logs.enabled=true
sentry.micrometer.enabled=true
sentry.micrometer.poll-interval-millis=1000
sentry.profile-session-sample-rate=1.0
sentry.profiling-traces-dir-path=tmp/sentry/profiling-traces
sentry.profile-lifecycle=TRACE
Expand Down
Loading
Loading