Skip to content

Instantly share code, notes, and snippets.

@nordfjord
Created July 12, 2023 14:41
Show Gist options
  • Save nordfjord/d5a0356e5112414892ead24b3405bbf2 to your computer and use it in GitHub Desktop.
Save nordfjord/d5a0356e5112414892ead24b3405bbf2 to your computer and use it in GitHub Desktop.
Span processor for json logs
export const processor = {
/**
* Forces to export all finished spans
*/
forceFlush() { return Promise.resolve() },
/**
* Called when a {@link Span} is started, if the `span.isRecording()`
* returns true.
* @param span the Span that just started.
*/
onStart() {},
/**
* Called when a {@link ReadableSpan} is ended, if the `span.isRecording()`
* returns true.
* @param {import('@opentelemetry/sdk-trace-base').ReadableSpan} span the Span that just ended.
*/
onEnd(span) {
const duration_ms = span.duration[0] * 1000 + span.duration[1] / 1000000;
const startTime = new Date(span.startTime[0] * 1000 + Math.round(span.startTime[1] / 1000000));
let kind = 'internal'
switch (span.kind) {
case SpanKind.CLIENT: kind = 'client'; break;
case SpanKind.SERVER: kind = 'server'; break;
case SpanKind.CONSUMER: kind = 'consumer'; break;
case SpanKind.PRODUCER: kind = 'producer'; break;
}
const context = span.spanContext()
console.log(JSON.stringify({
'name': span.name,
'duration_ms': duration_ms,
'start_time': startTime.toISOString(),
...span.attributes,
...span.resource.attributes,
'span.kind': kind,
'library.name': span.instrumentationLibrary.name,
'library.version': span.instrumentationLibrary.version,
'trace.trace_id': context.traceId,
'trace.span_id': context.spanId,
'trace.parent_id': span.parentSpanId,
'error': span.status.code !== 0,
'status_message': span.status.message,
}))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment