Last active
November 20, 2023 18:12
-
-
Save maksimr/5105ea7dd20607694604abe63632065a to your computer and use it in GitHub Desktop.
node tracer example
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 express from "express"; | |
import bodyParser from "body-parser"; | |
import { trace, context } from "@opentelemetry/api"; | |
import { BasicTracerProvider, ConsoleSpanExporter, SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base"; | |
import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks'; | |
const provider = new BasicTracerProvider(); | |
provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter())); | |
trace.setGlobalTracerProvider(provider); | |
async function main() { | |
const tracerContext = new AsyncLocalStorageContextManager(); | |
const tracer = trace.getTracer('service-foo'); | |
const app = express(); | |
const wrap = fn => async (req, res, next) => { | |
try { | |
await fn(req, res, next); | |
} catch (error) { | |
next(error); | |
} | |
}; | |
app.use(bodyParser.json()); | |
app.disable('etag'); | |
app.disable('x-powered-by'); | |
tracerContext.enable(); | |
context.setGlobalContextManager(tracerContext); | |
const wrapSpan = (name, fn, { options, context } = {}) => { | |
return function(...args) { | |
const thisCtx = this; | |
return tracer.startActiveSpan(name, options, context, (span) => { | |
try { | |
const result = fn.call(thisCtx, ...args); | |
if (result instanceof Promise) | |
result.finally(() => span.end()); | |
return result; | |
} catch (error) { | |
span.end(); | |
throw error; | |
} | |
}); | |
} | |
} | |
const dbQuery = wrapSpan('database', async (query) => { | |
trace.getActiveSpan().setAttribute('db.query', query); | |
await new Promise(resolve => setTimeout(resolve)); | |
}); | |
app.use(wrap(wrapSpan('request', async (req, res, next) => { | |
trace.getActiveSpan().setAttribute('http.method', req.method); | |
await next(); | |
}))); | |
app.get('/', wrap(wrapSpan('foo', async (req, res) => { | |
await dbQuery(req.path); | |
res.json({ | |
path: req.path | |
}); | |
}))); | |
app.listen(3000, () => { | |
console.log("Server started on port 3000"); | |
}); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment