Created
December 16, 2019 04:30
-
-
Save yamadayuki/203fe2772e57fd9b2f83522f4e33eea8 to your computer and use it in GitHub Desktop.
How to use OpenCensus packages in Node.js
This file contains 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 { CoreTracer, Span, Tracer } from "@opencensus/core"; | |
import { StackdriverTraceExporter } from "@opencensus/exporter-stackdriver"; | |
import { TracingBase } from "@opencensus/nodejs-base"; | |
import { TraceContextFormat } from "@opencensus/propagation-tracecontext"; | |
import { Request } from "express"; | |
import { ServerResponse } from "http"; | |
function getOperationName(req: Request): string | undefined { | |
if (req.baseUrl === "/graphql" && req.method === "POST") { | |
return req.body.operationName; | |
} | |
} | |
class Tracing extends TracingBase { | |
public readonly tracer: Tracer; | |
constructor() { | |
super([]); // Default list of target modules to be instrumented | |
this.tracer = new CoreTracer(); | |
} | |
} | |
function startTracing() { | |
const propagation = new TraceContextFormat(); | |
const encoded = process.env.JSON_KEY_BASE64; | |
const projectId = process.env.PROJECT_ID; | |
let exporter: StackdriverTraceExporter; | |
if (encoded && projectId) { | |
const credentials = JSON.parse(Buffer.from(encoded, "base64").toString()); | |
exporter = new StackdriverTraceExporter({ projectId, credentials }); | |
} | |
const tracing = Tracing.instance; | |
const httpConfig = { | |
ignoreIncomingPaths: ["/ping"], | |
applyCustomAttributesOnSpan(span: Span, req: Request, _res: ServerResponse) { | |
if (req) { | |
const operationName = getOperationName(req); | |
if (operationName) { | |
span.addAttribute("graphql.operation_name", operationName); | |
} | |
} | |
}, | |
}; | |
tracing.start({ | |
propagation, | |
exporter, | |
defaultAttributes: { commit_hash: process.env.COMMIT_HASH }, | |
plugins: { | |
http: { | |
module: "@opencensus/instrumentation-http", | |
config: httpConfig, | |
}, | |
https: { | |
module: "@opencensus/instrumentation-https", | |
config: httpConfig, | |
}, | |
http2: { | |
module: "@opencensus/instrumentation-http2", | |
config: httpConfig, | |
}, | |
grpc: "@opencensus/instrumentation-grpc", | |
}, | |
}); | |
tracing.tracer.registerSpanEventListener({ | |
onStartSpan(span) { | |
span.addAttribute("request_id", span.traceId); | |
}, | |
onEndSpan(_span) { | |
// noop | |
}, | |
}); | |
return tracing; | |
} | |
export const tracing = startTracing(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment