|
| 1 | +package io.sentry.util; |
| 2 | + |
| 3 | +import io.sentry.SentryAttribute; |
| 4 | +import io.sentry.SentryAttributes; |
| 5 | +import io.sentry.SentryEvent; |
| 6 | +import java.util.List; |
| 7 | +import java.util.Map; |
| 8 | +import org.jetbrains.annotations.ApiStatus; |
| 9 | +import org.jetbrains.annotations.NotNull; |
| 10 | +import org.jetbrains.annotations.Nullable; |
| 11 | + |
| 12 | +/** Utility class for applying logger properties (e.g. MDC) to Sentry events and log attributes. */ |
| 13 | +@ApiStatus.Internal |
| 14 | +public final class LoggerPropertiesUtil { |
| 15 | + |
| 16 | + /** |
| 17 | + * Applies logger properties from a map to a Sentry event as tags and context. The properties that |
| 18 | + * have keys matching any of the `targetKeys` will be applied as tags, while the others will be |
| 19 | + * reported in the `MDC` context. |
| 20 | + * |
| 21 | + * @param event the Sentry event to add tags to |
| 22 | + * @param targetKeys the list of property keys to apply as tags |
| 23 | + * @param properties the properties map (e.g. MDC) - this map will be modified by removing |
| 24 | + * properties which were applied as tags |
| 25 | + */ |
| 26 | + @ApiStatus.Internal |
| 27 | + public static void applyPropertiesToEvent( |
| 28 | + final @NotNull SentryEvent event, |
| 29 | + final @NotNull List<String> targetKeys, |
| 30 | + final @NotNull Map<String, String> properties) { |
| 31 | + if (!targetKeys.isEmpty() && !properties.isEmpty()) { |
| 32 | + for (final String key : targetKeys) { |
| 33 | + final @Nullable String value = properties.remove(key); |
| 34 | + if (value != null) { |
| 35 | + event.setTag(key, value); |
| 36 | + } |
| 37 | + } |
| 38 | + if (!properties.isEmpty()) { |
| 39 | + event.getContexts().put("MDC", properties); |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * Applies logger properties from a properties map to SentryAttributes for logs. Only the |
| 46 | + * properties with keys that are found in `targetKeys` will be applied as attributes. Properties |
| 47 | + * with null values are filtered out. |
| 48 | + * |
| 49 | + * @param attributes the SentryAttributes to add the properties to |
| 50 | + * @param targetKeys the list of property keys to apply as attributes |
| 51 | + * @param properties the properties map (e.g. MDC) |
| 52 | + */ |
| 53 | + @ApiStatus.Internal |
| 54 | + public static void applyPropertiesToAttributes( |
| 55 | + final @NotNull SentryAttributes attributes, |
| 56 | + final @NotNull List<String> targetKeys, |
| 57 | + final @NotNull Map<String, String> properties) { |
| 58 | + if (!targetKeys.isEmpty() && !properties.isEmpty()) { |
| 59 | + for (final String key : targetKeys) { |
| 60 | + final @Nullable String value = properties.get(key); |
| 61 | + if (value != null) { |
| 62 | + attributes.add(SentryAttribute.stringAttribute("mdc." + key, value)); |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments