参考文档
https://help.aliyun.com/document_detail/611711.html?spm=a2c4g.90499.0.0.34a056ddTu2WWq
先按照 方法一:手动埋点上报Python应用数据 步骤测试上报是否正常。
flas 上报
在 手动埋点上报Python应用数据 的基础上,上报flask应用的数据,因为上边的文档只有django的,所以在这里记录一下。
安装依赖
pip install opentelemetry-api
pip install opentelemetry-sdk
pip install opentelemetry-exporter-otlp
pip install opentelemetry-instrumentation-flask
pip install opentelemetry-instrumentation-requests
flask 中使用opentelemetry上报
import flask
import requests
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter as OTLPSpanGrpcExporter
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter as OTLPSpanHttpExporter
from opentelemetry.instrumentation.flask import FlaskInstrumentor
from opentelemetry.instrumentation.requests import RequestsInstrumentor
from opentelemetry.sdk.resources import SERVICE_NAME, Resource, HOST_NAME
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessordef initTracer():resource = Resource(attributes={SERVICE_NAME: "aaaaaaaa",HOST_NAME: "flasksss"})# 使用GRPC协议上报span_processor = BatchSpanProcessor(OTLPSpanGrpcExporter(endpoint="http://tracing-analysis-dc-hz.aliyuncs.com:8090",headers=("Authentication=emyaq87zvp@84d4c400bdb6eed_emyaq87zvp@53df7ad2afe8301")))# 使用HTTP协议上报# span_processor = BatchSpanProcessor(OTLPSpanHttpExporter(# endpoint="<endpoint>",# ))trace_provider = TracerProvider(resource=resource, active_span_processor=span_processor)trace.set_tracer_provider(trace_provider)# flask init
app = flask.Flask(__name__)# instrumentation init
initTracer()
FlaskInstrumentor().instrument_app(app)
RequestsInstrumentor().instrument()@app.route("/")
def hello():tracer = trace.get_tracer(__name__)# 上报requests请求with tracer.start_as_current_span("request_server"):requests.get("http://www.taobao.com")print(11111111111)return "hello"@app.route("/acb")
def aabc():return 'abc'app.run(debug=True, port=5001, host='0.0.0.0')
代码解释
- initTrace函数:初始化上报功能,参数意义参见 方法一:手动埋点上报Python应用数据
效果展示
遇到问题解决:
出现这个问题好像是用GRPC协议上报的时候rpc出问题了,改成用HTTP协议上报上报就可以了。
不同的上报协议endpoint的值不一样哦,要填对。