|
| 1 | +package com.appsmith.server.aspect; |
| 2 | + |
| 3 | +import io.opentelemetry.api.GlobalOpenTelemetry; |
| 4 | +import io.opentelemetry.api.trace.Span; |
| 5 | +import io.opentelemetry.api.trace.Tracer; |
| 6 | +import io.opentelemetry.context.Scope; |
| 7 | +import org.aspectj.lang.ProceedingJoinPoint; |
| 8 | +import org.aspectj.lang.annotation.Around; |
| 9 | +import org.aspectj.lang.annotation.Aspect; |
| 10 | +import org.aspectj.lang.annotation.Pointcut; |
| 11 | + |
| 12 | +@Aspect |
| 13 | +public class TelemetryAspect { |
| 14 | + |
| 15 | + private static final Tracer tracer = GlobalOpenTelemetry.getTracer("appsmith"); |
| 16 | + private static final long DEFAULT_THRESHOLD_NS = 1_000_000L; |
| 17 | + private static final long thresholdNanoseconds = Long.parseLong( |
| 18 | + System.getenv().getOrDefault("TELEMETRY_THRESHOLD_NANOSECONDS", String.valueOf(DEFAULT_THRESHOLD_NS)) |
| 19 | + ); |
| 20 | + |
| 21 | + @Pointcut("execution(* org.eclipse.jgit..*(..))") |
| 22 | + public void monitoredAppsmithMethods() {} |
| 23 | + |
| 24 | + @Around("monitoredAppsmithMethods()") |
| 25 | + public Object traceAppsmithBusinessLogic(ProceedingJoinPoint joinPoint) throws Throwable { |
| 26 | + long startTime = System.nanoTime(); |
| 27 | + |
| 28 | + Object result; |
| 29 | + Throwable caughtException = null; |
| 30 | + try { |
| 31 | + result = joinPoint.proceed(); |
| 32 | + } catch (Throwable t) { |
| 33 | + caughtException = t; |
| 34 | + throw t; |
| 35 | + } finally { |
| 36 | + long duration = System.nanoTime() - startTime; |
| 37 | + if (duration > thresholdNanoseconds) { |
| 38 | + String spanName = getSpanName(joinPoint); |
| 39 | + |
| 40 | + Span span = tracer.spanBuilder(spanName).startSpan(); |
| 41 | + |
| 42 | + try (Scope scope = span.makeCurrent()) { |
| 43 | + span.setAttribute("execution.time.ns", duration); |
| 44 | + if (caughtException != null) { |
| 45 | + span.recordException(caughtException); |
| 46 | + } |
| 47 | + logSpan(span, spanName, duration); |
| 48 | + } finally { |
| 49 | + span.end(); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + return result; |
| 55 | + } |
| 56 | + |
| 57 | + private String getSpanName(ProceedingJoinPoint joinPoint) { |
| 58 | + return joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName(); |
| 59 | + } |
| 60 | + |
| 61 | + private void logSpan(Span span, String spanName, long duration) { |
| 62 | + System.out.println("🚀 " + span.getSpanContext().getTraceId() + " > " |
| 63 | + + span.getSpanContext().getSpanId() + " > " + spanName + " took: " + duration + " ns"); |
| 64 | + } |
| 65 | +} |
0 commit comments