|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright 2021 The OpenTelemetry Authors |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +# [START opentelemetry_flask_import] |
| 17 | + |
| 18 | +import time |
| 19 | + |
| 20 | +from flask import Flask |
| 21 | +from opentelemetry import trace |
| 22 | +from opentelemetry.exporter.cloud_trace import CloudTraceSpanExporter |
| 23 | +from opentelemetry.instrumentation.flask import FlaskInstrumentor |
| 24 | +from opentelemetry.propagate import set_global_textmap |
| 25 | +from opentelemetry.propagators.cloud_trace_propagator import ( |
| 26 | + CloudTraceFormatPropagator, |
| 27 | +) |
| 28 | +from opentelemetry.sdk.trace import TracerProvider |
| 29 | +from opentelemetry.sdk.trace.export import BatchSpanProcessor |
| 30 | + |
| 31 | +# [END opentelemetry_flask_import] |
| 32 | + |
| 33 | +# [START opentelemetry_flask_setup_propagator] |
| 34 | + |
| 35 | +set_global_textmap(CloudTraceFormatPropagator()) |
| 36 | + |
| 37 | +# [END opentelemetry_flask_setup_propagator] |
| 38 | + |
| 39 | +# [START opentelemetry_flask_setup_exporter] |
| 40 | + |
| 41 | +tracer_provider = TracerProvider() |
| 42 | +cloud_trace_exporter = CloudTraceSpanExporter() |
| 43 | +tracer_provider.add_span_processor( |
| 44 | + # BatchSpanProcessor buffers spans and sends them in batches in a |
| 45 | + # background thread. The default parameters are sensible, but can be |
| 46 | + # tweaked to optimize your performance |
| 47 | + BatchSpanProcessor(cloud_trace_exporter) |
| 48 | +) |
| 49 | +trace.set_tracer_provider(tracer_provider) |
| 50 | + |
| 51 | +tracer = trace.get_tracer(__name__) |
| 52 | + |
| 53 | +# [END opentelemetry_flask_setup_exporter] |
| 54 | + |
| 55 | +# [START opentelemetry_flask_instrument] |
| 56 | + |
| 57 | +app = Flask(__name__) |
| 58 | +FlaskInstrumentor().instrument_app(app) |
| 59 | + |
| 60 | + |
| 61 | +@app.route("/") |
| 62 | +def hello_world(): |
| 63 | + # You can still use the OpenTelemetry API as usual to create custom spans |
| 64 | + # within your trace |
| 65 | + with tracer.start_as_current_span("do_work"): |
| 66 | + time.sleep(0.1) |
| 67 | + |
| 68 | + return "Hello, World!" |
| 69 | + |
| 70 | + |
| 71 | +# [END opentelemetry_flask_instrument] |
0 commit comments