Last active
November 22, 2023 11:43
-
-
Save wellwind/7bbd96692d788482bc1fe97c02f3a53b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyTrace { | |
private spanMap = new Map<string, Span>(); | |
private readonly tracerName = 'my_tracer'; | |
constructor(private otel: OTELApi) {} | |
createSingleRunSpan(spanName: string) { | |
const span = this.otel.trace.getTracer(this.tracerName).startSpan(spanName); | |
const end = () => span.end(); | |
return { span, end }; | |
} | |
createRootSpan(spanName: string) { | |
if (this.spanMap.has(spanName)) { | |
throw new Error(`Span with name ${spanName} already exists`); | |
} | |
const span = this.otel.trace.getTracer(this.tracerName).startSpan(spanName); | |
this.spanMap.set(spanName, span); | |
return span; | |
} | |
createChildSpan(spanName: string, parentSpanName: string) { | |
if (this.spanMap.has(spanName)) { | |
throw new Error(`[Span] Span with name ${spanName} already exists`); | |
} | |
if (!this.spanMap.has(parentSpanName)) { | |
throw new Error( | |
`[Parent Span] Span with name ${parentSpanName} does not exist` | |
); | |
} | |
const context = this.otel.trace.setSpan( | |
this.otel.context.active(), | |
this.spanMap.get(parentSpanName)! | |
); | |
const span = this.otel.trace | |
.getTracer(this.tracerName) | |
.startSpan(spanName, {}, context); | |
this.spanMap.set(spanName, span); | |
return span; | |
} | |
endSpan(spanName: string) { | |
if (!this.spanMap.has(spanName)) { | |
throw new Error(`Span with name ${spanName} does not exist`); | |
} | |
const span = this.spanMap.get(spanName); | |
span!.end(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment