flask_prometheus_app.py
· 672 B · Python
Originalformat
from flask import Flask, Response
from prometheus_client import Counter, Summary, generate_latest, CONTENT_TYPE_LATEST
import time
app = Flask(__name__)
# 自訂 metrics
REQUEST_COUNT = Counter('app_requests_total', 'Total number of requests')
REQUEST_LATENCY = Summary('app_request_latency_seconds', 'Request latency')
@app.route('/')
@REQUEST_LATENCY.time() # 測量延遲
def hello():
REQUEST_COUNT.inc() # 計數器 +1
time.sleep(0.2) # 模擬延遲
return "Hello World!"
@app.route("/metrics")
def metrics():
return Response(generate_latest(), mimetype=CONTENT_TYPE_LATEST)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)
| 1 | from flask import Flask, Response |
| 2 | from prometheus_client import Counter, Summary, generate_latest, CONTENT_TYPE_LATEST |
| 3 | import time |
| 4 | |
| 5 | app = Flask(__name__) |
| 6 | |
| 7 | # 自訂 metrics |
| 8 | REQUEST_COUNT = Counter('app_requests_total', 'Total number of requests') |
| 9 | REQUEST_LATENCY = Summary('app_request_latency_seconds', 'Request latency') |
| 10 | |
| 11 | @app.route('/') |
| 12 | @REQUEST_LATENCY.time() # 測量延遲 |
| 13 | def hello(): |
| 14 | REQUEST_COUNT.inc() # 計數器 +1 |
| 15 | time.sleep(0.2) # 模擬延遲 |
| 16 | return "Hello World!" |
| 17 | |
| 18 | @app.route("/metrics") |
| 19 | def metrics(): |
| 20 | return Response(generate_latest(), mimetype=CONTENT_TYPE_LATEST) |
| 21 | |
| 22 | if __name__ == '__main__': |
| 23 | app.run(host='0.0.0.0', port=8000) |