46 lines
1.3 KiB
JavaScript
46 lines
1.3 KiB
JavaScript
'use strict';
|
|
|
|
const api = require('@opentelemetry/api');
|
|
const tracer = require('./tracer')('example-http-server');
|
|
const http = require('http');
|
|
|
|
/** Starts a HTTP server that receives requests on sample server port. */
|
|
function startServer(port) {
|
|
// Creates a server
|
|
const server = http.createServer(handleRequest);
|
|
// Starts the server
|
|
server.listen(port, (err) => {
|
|
if (err) {
|
|
throw err;
|
|
}
|
|
console.log(`Node HTTP listening on ${port}`);
|
|
});
|
|
}
|
|
|
|
/** A function which handles requests and send response. */
|
|
function handleRequest(request, response) {
|
|
const currentSpan = api.trace.getActiveSpan();
|
|
// display traceid in the terminal
|
|
const traceId = currentSpan.spanContext().traceId;
|
|
console.log(`traceId: ${traceId}`);
|
|
const span = tracer.startSpan('handleRequest', {
|
|
kind: 1, // server
|
|
attributes: { key: 'value' },
|
|
});
|
|
// Annotate our span to capture metadata about the operation
|
|
span.addEvent('invoking handleRequest');
|
|
|
|
const body = [];
|
|
request.on('error', (err) => console.log(err));
|
|
request.on('data', (chunk) => body.push(chunk));
|
|
request.on('end', () => {
|
|
// deliberately sleeping to mock some action.
|
|
setTimeout(() => {
|
|
span.end();
|
|
response.end('Hello World!');
|
|
}, 2000);
|
|
});
|
|
}
|
|
|
|
startServer(8080);
|