Carlos Aguni

Highly motivated self-taught IT analyst. Always learning and ready to explore new skills. An eternal apprentice.


Flask Otel Instrumentation

13 Aug 2022 »

Working flask instrumentation

https://www.logicmonitor.com/blog/flask-application-manual-instrumentation-for-distributed-traces?utm_medium=organic-social&utm_source=everyonesocial&utm_term=na&utm_content=na&utm_campaign=2021_Organic-Social-EveryoneSocial_Blog&es_id=521eb4aa57


export LM_OTEL_ENDPOINT=http://10.7.0.24:4317

export OTEL_RESOURCE_ATTRIBUTES=service.namespace=opentelemetry,service.name=instrument-flask-app,host.name=localhost


pip install flask
pip install opentelemetry-api
pip install opentelemetry-sdk
pip install opentelemetry-instrumentation-flask
pip install opentelemetry-exporter-otlp

app.py

from flask import Flask, jsonify, request
from flask_cors import CORS
from opentelemetry import trace
from opentelemetry.instrumentation.flask import FlaskInstrumentor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor,ConsoleSpanExporter
import os

app = Flask(__name__) 
CORS(app)
FlaskInstrumentor().instrument_app(app)
trace.set_tracer_provider(TracerProvider())



# To print the traces on the console
trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(ConsoleSpanExporter()))

# To send the traces to the configured OTEL collector
trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(
OTLPSpanExporter(endpoint=os.environ.get("LM_OTEL_ENDPOINT"), insecure=True)))

@app.route("/")  
def hello():  
    return jsonify({"a": 2})
    return "Hello World!"  


if __name__ == "__main__":  
   app.run(port=8081, host='0.0.0.0')