|
| 1 | +/* |
| 2 | + * Copyright The OpenTelemetry Authors |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +package io.opentelemetry.instrumentation.api.incubator.semconv.util; |
| 7 | + |
| 8 | +import io.opentelemetry.instrumentation.api.internal.ClassNames; |
| 9 | +import io.opentelemetry.instrumentation.api.internal.cache.Cache; |
| 10 | + |
| 11 | +import java.lang.reflect.Method; |
| 12 | +import java.util.Map; |
| 13 | +import java.util.concurrent.ConcurrentHashMap; |
| 14 | + |
| 15 | +@Deprecated |
| 16 | +public final class SpanNames { |
| 17 | + |
| 18 | + private static final Cache<Class<?>, Map<String, String>> spanNameCaches = Cache.weak(); |
| 19 | + |
| 20 | + /** |
| 21 | + * This method is used to generate a span name based on a method. Anonymous classes are named |
| 22 | + * based on their parent. |
| 23 | + */ |
| 24 | + public static String fromMethod(Method method) { |
| 25 | + return fromMethod(method.getDeclaringClass(), method.getName()); |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * This method is used to generate a span name based on a method. Anonymous classes are named |
| 30 | + * based on their parent. |
| 31 | + */ |
| 32 | + public static String fromMethod(Class<?> clazz, String methodName) { |
| 33 | + // the cache (ConcurrentHashMap) is naturally bounded by the number of methods in a class |
| 34 | + Map<String, String> spanNameCache = |
| 35 | + spanNameCaches.computeIfAbsent(clazz, c -> new ConcurrentHashMap<>()); |
| 36 | + |
| 37 | + // not using computeIfAbsent, because it would require a capturing (allocating) lambda |
| 38 | + String spanName = spanNameCache.get(methodName); |
| 39 | + if (spanName != null) { |
| 40 | + return spanName; |
| 41 | + } |
| 42 | + spanName = ClassNames.simpleName(clazz) + "." + methodName; |
| 43 | + spanNameCache.put(methodName, spanName); |
| 44 | + return spanName; |
| 45 | + } |
| 46 | + |
| 47 | + private SpanNames() {} |
| 48 | +} |
0 commit comments