Skip to content

Instantly share code, notes, and snippets.

@yamadayuki
Created December 16, 2019 04:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yamadayuki/203fe2772e57fd9b2f83522f4e33eea8 to your computer and use it in GitHub Desktop.
Save yamadayuki/203fe2772e57fd9b2f83522f4e33eea8 to your computer and use it in GitHub Desktop.
How to use OpenCensus packages in Node.js
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