|
| 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 | + |
| 11 | +/** Utility class for applying logger properties (e.g. MDC) to Sentry events and log attributes. */ |
| 12 | +@ApiStatus.Internal |
| 13 | +public final class LoggerPropertiesUtil { |
| 14 | + |
| 15 | + /** |
| 16 | + * Applies logger properties from a map to a Sentry event as tags. Only the properties with keys |
| 17 | + * that are found in `targetKeys` will be applied as tags. |
| 18 | + * |
| 19 | + * @param event the Sentry event to add tags to |
| 20 | + * @param targetKeys the list of property keys to apply as tags |
| 21 | + * @param properties the properties map (e.g. MDC) - this map will be modified by removing |
| 22 | + * properties which were applied as tags |
| 23 | + */ |
| 24 | + @ApiStatus.Internal |
| 25 | + public static void applyPropertiesToEvent( |
| 26 | + final @NotNull SentryEvent event, |
| 27 | + final @NotNull List<String> targetKeys, |
| 28 | + final @NotNull Map<String, String> properties) { |
| 29 | + if (!targetKeys.isEmpty() && !properties.isEmpty()) { |
| 30 | + for (final String key : targetKeys) { |
| 31 | + if (properties.containsKey(key)) { |
| 32 | + event.setTag(key, properties.get(key)); |
| 33 | + properties.remove(key); |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * Applies logger properties from a properties map to SentryAttributes for logs. Properties with |
| 41 | + * null values are filtered out. |
| 42 | + * |
| 43 | + * @param attributes the SentryAttributes to add the properties to |
| 44 | + * @param properties the properties map (e.g. MDC) |
| 45 | + */ |
| 46 | + @ApiStatus.Internal |
| 47 | + public static void applyPropertiesToAttributes( |
| 48 | + final @NotNull SentryAttributes attributes, final @NotNull Map<String, String> properties) { |
| 49 | + for (final Map.Entry<String, String> entry : properties.entrySet()) { |
| 50 | + if (entry.getValue() != null) { |
| 51 | + attributes.add(SentryAttribute.stringAttribute(entry.getKey(), entry.getValue())); |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments