Skip to content
This repository was archived by the owner on Nov 10, 2022. It is now read-only.

Commit 17ccb3a

Browse files
cartermpdyladan
andauthored
feat: Add getActiveSpan to trace API (#163)
Co-authored-by: Daniel Dyla <[email protected]>
1 parent bafcf0d commit 17ccb3a

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

src/api/trace.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import { Tracer } from '../trace/tracer';
2828
import { TracerProvider } from '../trace/tracer_provider';
2929
import {
3030
deleteSpan,
31+
getActiveSpan,
3132
getSpan,
3233
getSpanContext,
3334
setSpan,
@@ -102,6 +103,8 @@ export class TraceAPI {
102103

103104
public getSpan = getSpan;
104105

106+
public getActiveSpan = getActiveSpan;
107+
105108
public getSpanContext = getSpanContext;
106109

107110
public setSpan = setSpan;

src/trace/context-utils.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import { Context } from '../context/types';
1919
import { Span } from './span';
2020
import { SpanContext } from './span_context';
2121
import { NonRecordingSpan } from './NonRecordingSpan';
22+
import { ContextAPI } from '../api/context';
2223

2324
/**
2425
* span key
@@ -34,6 +35,13 @@ export function getSpan(context: Context): Span | undefined {
3435
return (context.getValue(SPAN_KEY) as Span) || undefined;
3536
}
3637

38+
/**
39+
* Gets the span from the current context, if one exists.
40+
*/
41+
export function getActiveSpan(): Span | undefined {
42+
return getSpan(ContextAPI.getInstance().active());
43+
}
44+
3745
/**
3846
* Set the span on a context
3947
*

test/api/api.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,17 @@ describe('API', () => {
5252
assert.strictEqual(typeof tracer, 'object');
5353
});
5454

55+
it('getActiveSpan should get the current span', () => {
56+
const span = new NonRecordingSpan();
57+
const ctx = trace.setSpan(ROOT_CONTEXT, span);
58+
context.setGlobalContextManager({ active: () => ctx, disable: () => {} } as any);
59+
60+
const active = trace.getActiveSpan();
61+
assert.strictEqual(active, span);
62+
63+
context.disable();
64+
});
65+
5566
describe('Context', () => {
5667
it('with should forward this, arguments and return value', () => {
5768
function fnWithThis(this: string, a: string, b: number): string {

0 commit comments

Comments
 (0)