Skip to content

Latest commit

 

History

History
88 lines (65 loc) · 3.04 KB

INSTALL_OTEL_STEP2.md

File metadata and controls

88 lines (65 loc) · 3.04 KB

INSTALLING OPENTELEMETRY STEP 2

CUSTOM ATTRIBUTES, EVENTS AND SPANS

In this step, we will add to our spans custom attributes and log events. We will also create custom spans.

Add custom attributes using environment variables

  • Edit docker-compose.yml file, go to the environment section of services web and service

  • For each service, add an environment variable OTEL_RESOURCE_ATTRIBUTES with value a list of comma separated <key>=<value>

  • Example:

  web:
    environment:
     - OTEL_RESOURCE_ATTRIBUTES=service.name=web,service.version=2.0.0

Add custom attributes in code

  • In /src folder of the web component, update file index.js file with code below:

    • Add the OpenTelemetry library by putting this at top of your code
    // import the open telemetry api library
    const api = require('@opentelemetry/api');
    // create a tracer and name it after your package
    const tracer = api.trace.getTracer('myInstrumentation');
    • in the main() function, in the app.get("/", (req, res) => { part, add code to create custom attributes
    // access the current span from active context
    let activeSpan = api.trace.getSpan(api.context.active());
    // add an attribute
    activeSpan.setAttribute('nbLoop', nbLoop);
    activeSpan.setAttribute('weather', weather);

Add log events

  • In the main() function, in the app.get("/api/data", (req, res) => { part, add code to create custom log events
  // access the current span from active context
  let activeSpan = api.trace.getSpan(api.context.active());
  // log an event and include some structured data.
  activeSpan.addEvent('Running on http://${HOST}:${PORT}');

Create spans

  • Replace the generateWork function with code below
async function generateWork(nb) {
  for (let i = 0; i < Number(nb); i++) {
    // create a new span
    // if not put as arg, current span is automatically used as parent
    // and the span you create automatically become the current one
    let span = tracer.startSpan(`Looping ${i}`);
    // log an event and include some structured data. This replace the logger to file
    span.addEvent(`*** DOING SOMETHING ${i}`);
    // wait for 50ms to simulate some work
    await sleep(50);
    // don't forget to always end the span to flush data out
    span.end();
  }
}

Test