|
| 1 | +# Copyright 2021 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 | +# https://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 | +# [START monitoring_sli_metrics_prometheus_setup] |
| 15 | +import random |
| 16 | +import time |
| 17 | + |
| 18 | +from flask import Flask |
| 19 | + |
| 20 | +from prometheus_client import ( |
| 21 | + Counter, |
| 22 | + generate_latest, |
| 23 | + Histogram, |
| 24 | + REGISTRY, |
| 25 | +) |
| 26 | + |
| 27 | +# [END monitoring_sli_metrics_prometheus_setup] |
| 28 | + |
| 29 | +app = Flask(__name__) |
| 30 | +# [START monitoring_sli_metrics_prometheus_create_metrics] |
| 31 | +PYTHON_REQUESTS_COUNTER = Counter("python_requests", "total requests") |
| 32 | +PYTHON_FAILED_REQUESTS_COUNTER = Counter("python_failed_requests", "failed requests") |
| 33 | +PYTHON_LATENCIES_HISTOGRAM = Histogram( |
| 34 | + "python_request_latency", "request latency by path" |
| 35 | +) |
| 36 | +# [END monitoring_sli_metrics_prometheus_create_metrics] |
| 37 | + |
| 38 | + |
| 39 | +@app.route("/") |
| 40 | +# [START monitoring_sli_metrics_prometheus_latency] |
| 41 | +@PYTHON_LATENCIES_HISTOGRAM.time() |
| 42 | +# [END monitoring_sli_metrics_prometheus_latency] |
| 43 | +def homePage(): |
| 44 | + # count request |
| 45 | + # [START monitoring_sli_metrics_prometheus_counts] |
| 46 | + PYTHON_REQUESTS_COUNTER.inc() |
| 47 | + # fail 10% of the time |
| 48 | + if random.randint(0, 100) > 90: |
| 49 | + PYTHON_FAILED_REQUESTS_COUNTER.inc() |
| 50 | + # [END monitoring_sli_metrics_prometheus_counts] |
| 51 | + return ("error!", 500) |
| 52 | + else: |
| 53 | + random_delay = random.randint(0, 5000) / 1000 |
| 54 | + # delay for a bit to vary latency measurement |
| 55 | + time.sleep(random_delay) |
| 56 | + return "home page" |
| 57 | + |
| 58 | + |
| 59 | +# [START monitoring_sli_metrics_prometheus_metrics_endpoint] |
| 60 | +@app.route("/metrics", methods=["GET"]) |
| 61 | +def stats(): |
| 62 | + return generate_latest(REGISTRY), 200 |
| 63 | + |
| 64 | + |
| 65 | +# [END monitoring_sli_metrics_prometheus_metrics_endpoint] |
| 66 | + |
| 67 | + |
| 68 | +if __name__ == "__main__": |
| 69 | + app.run(debug=True, host="0.0.0.0", port=8080) |
0 commit comments