|
| 1 | +# Copyright 2020 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import argparse |
| 16 | +import os |
| 17 | +import random |
| 18 | +import time |
| 19 | + |
| 20 | +from flask import Flask, redirect, url_for |
| 21 | + |
| 22 | +# [START trace_setup_python_configure] |
| 23 | +from opentelemetry import trace |
| 24 | +from opentelemetry.exporter.cloud_trace import CloudTraceSpanExporter |
| 25 | +from opentelemetry.sdk.trace import TracerProvider |
| 26 | +from opentelemetry.sdk.trace.export import SimpleExportSpanProcessor |
| 27 | + |
| 28 | + |
| 29 | +def initialize_tracer(project_id): |
| 30 | + trace.set_tracer_provider(TracerProvider()) |
| 31 | + cloud_trace_exporter = CloudTraceSpanExporter(project_id) |
| 32 | + trace.get_tracer_provider().add_span_processor( |
| 33 | + SimpleExportSpanProcessor(cloud_trace_exporter) |
| 34 | + ) |
| 35 | + opentelemetry_tracer = trace.get_tracer(__name__) |
| 36 | + |
| 37 | + return opentelemetry_tracer |
| 38 | + |
| 39 | + |
| 40 | +# [END trace_setup_python_configure] |
| 41 | + |
| 42 | +app = Flask(__name__) |
| 43 | + |
| 44 | + |
| 45 | +@app.route("/", methods=["GET"]) |
| 46 | +def root(): |
| 47 | + return redirect(url_for("index")) |
| 48 | + |
| 49 | + |
| 50 | +# [START trace_setup_python_quickstart] |
| 51 | +@app.route("/index.html", methods=["GET"]) |
| 52 | +def index(): |
| 53 | + tracer = app.config["TRACER"] |
| 54 | + tracer.start_as_current_span(name="index") |
| 55 | + # Add up to 1 sec delay, weighted toward zero |
| 56 | + time.sleep(random.random() ** 2) |
| 57 | + result = "Tracing requests" |
| 58 | + |
| 59 | + return result |
| 60 | + |
| 61 | + |
| 62 | +# [END trace_setup_python_quickstart] |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + parser = argparse.ArgumentParser( |
| 67 | + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter |
| 68 | + ) |
| 69 | + parser.add_argument( |
| 70 | + "--project_id", |
| 71 | + help="Project ID you want to access.", |
| 72 | + default=os.environ["GOOGLE_CLOUD_PROJECT"], |
| 73 | + required=True, |
| 74 | + ) |
| 75 | + args = parser.parse_args() |
| 76 | + |
| 77 | + tracer = initialize_tracer(args.project_id) |
| 78 | + app.config["TRACER"] = tracer |
| 79 | + |
| 80 | + app.run() |
0 commit comments