diff --git a/src/api/trace.ts b/src/api/trace.ts index b97fe0a..492c16b 100644 --- a/src/api/trace.ts +++ b/src/api/trace.ts @@ -28,6 +28,7 @@ import { Tracer } from '../trace/tracer'; import { TracerProvider } from '../trace/tracer_provider'; import { deleteSpan, + getActiveSpan, getSpan, getSpanContext, setSpan, @@ -102,6 +103,8 @@ export class TraceAPI { public getSpan = getSpan; + public getActiveSpan = getActiveSpan; + public getSpanContext = getSpanContext; public setSpan = setSpan; diff --git a/src/trace/context-utils.ts b/src/trace/context-utils.ts index 1d24bc2..83bd551 100644 --- a/src/trace/context-utils.ts +++ b/src/trace/context-utils.ts @@ -19,6 +19,7 @@ import { Context } from '../context/types'; import { Span } from './span'; import { SpanContext } from './span_context'; import { NonRecordingSpan } from './NonRecordingSpan'; +import { ContextAPI } from '../api/context'; /** * span key @@ -34,6 +35,13 @@ export function getSpan(context: Context): Span | undefined { return (context.getValue(SPAN_KEY) as Span) || undefined; } +/** + * Gets the span from the current context, if one exists. + */ +export function getActiveSpan(): Span | undefined { + return getSpan(ContextAPI.getInstance().active()); +} + /** * Set the span on a context * diff --git a/test/api/api.test.ts b/test/api/api.test.ts index 4feacd1..4f51462 100644 --- a/test/api/api.test.ts +++ b/test/api/api.test.ts @@ -52,6 +52,17 @@ describe('API', () => { assert.strictEqual(typeof tracer, 'object'); }); + it('getActiveSpan should get the current span', () => { + const span = new NonRecordingSpan(); + const ctx = trace.setSpan(ROOT_CONTEXT, span); + context.setGlobalContextManager({ active: () => ctx, disable: () => {} } as any); + + const active = trace.getActiveSpan(); + assert.strictEqual(active, span); + + context.disable(); + }); + describe('Context', () => { it('with should forward this, arguments and return value', () => { function fnWithThis(this: string, a: string, b: number): string {