app.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from random import randint
  2. from flask import Flask, request
  3. import logging
  4. from opentelemetry import trace
  5. tracer = trace.get_tracer("diceroller.tracer")
  6. app = Flask(__name__)
  7. logging.basicConfig(level=logging.INFO)
  8. logger = logging.getLogger(__name__)
  9. @app.route("/rolldice")
  10. def roll_dice():
  11. player = request.args.get('player', default = None, type = str)
  12. result = str(roll3())
  13. if player:
  14. logger.warning("%s is rolling the dice: %s", player, result)
  15. else:
  16. logger.warning("Anonymous player is rolling the dice: %s", result)
  17. return result
  18. @tracer.start_as_current_span("roll")
  19. def roll():
  20. return randint(1, 6)
  21. def roll2():
  22. with tracer.start_as_current_span("roll") as rollspan:
  23. try:
  24. res = randint(1, 6)
  25. rollspan.set_status(trace.StatusCode.OK)
  26. rollspan.set_attribute("roll.value", res)
  27. rollspan.add_event("事件A")
  28. return res
  29. except Exception as ex:
  30. rollspan.set_status(trace.StatusCode.ERROR)
  31. rollspan.record_exception(ex)
  32. raise ex
  33. @tracer.start_as_current_span("roll")
  34. def roll3():
  35. # 其它业务代码...
  36. with tracer.start_as_current_span("randint") as randspan:
  37. try:
  38. res = randint(1, 6)
  39. randspan.set_status(trace.StatusCode.OK)
  40. randspan.set_attribute("roll.value", res)
  41. randspan.add_event("事件A")
  42. return res
  43. except Exception as ex:
  44. randspan.set_status(trace.StatusCode.ERROR)
  45. randspan.record_exception(ex)
  46. raise ex
  47. # 其它业务代码...