Created
November 26, 2018 18:54
-
-
Save ebenoist/00c8695e8750138f76ef3f4b97b135a1 to your computer and use it in GitHub Desktop.
gRPC / Datadog / Open Tracing Interceptor
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
import * as tracer from 'dd-trace'; | |
import * as opentracing from 'opentracing'; | |
import { InterceptingCall } from 'grpc'; | |
const TRACE_HEADER = 'x-datadog-trace-id'; | |
const PARENT_HEADER = 'x-datadog-parent-id'; | |
export default function gRPCInterceptor(options, nextCall) { | |
return new InterceptingCall(nextCall(options), { | |
start: (metadata, _listener, next) => { | |
const parentScope = tracer.scopeManager().active(); | |
const parent = parentScope && parentScope.span(); | |
const path = options.method_definition.path; | |
const service = path.split('/')[1].split('.').slice(-1)[0]; | |
const method = path.substring(1).replace(/[\/\.]/g, '_'); | |
const span = tracer.startSpan('grpc.client', { | |
childOf: parent, | |
tags: { | |
'service.name': service, | |
'resource.name': method, | |
'span.type': 'grpc', | |
}, | |
}); | |
const meta = {}; | |
tracer.scopeManager().activate(span); | |
tracer.inject(span, opentracing.FORMAT_HTTP_HEADERS, meta); | |
metadata.set(TRACE_HEADER, meta[TRACE_HEADER]); | |
metadata.set(PARENT_HEADER, meta[PARENT_HEADER]); | |
next(metadata, { | |
onReceiveStatus: (status, next) => { | |
span.finish(); | |
next(status); | |
}, | |
}); | |
}, | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment