|
| 1 | +from ...log import logger |
| 2 | +from ...sdk import sdk |
| 3 | + |
| 4 | +import os |
| 5 | + |
| 6 | + |
| 7 | +from bottle import hook, request, response |
| 8 | + |
| 9 | + |
| 10 | +def instrument(): |
| 11 | + @hook("before_request") |
| 12 | + def instrument_before_request(): |
| 13 | + try: |
| 14 | + # extract host and port from the request |
| 15 | + host = request.environ.get("HTTP_HOST", "unknown") |
| 16 | + app_name = "{}".format(host) |
| 17 | + |
| 18 | + virtual_host = os.environ.get("AUTODYNATRACE_VIRTUAL_HOST", "{}".format(host)) |
| 19 | + app_name = os.environ.get("AUTODYNATRACE_APPLICATION_ID", "Bottle ({})".format(app_name)) |
| 20 | + context_root = os.environ.get("AUTODYNATRACE_CONTEXT_ROOT", "/") |
| 21 | + |
| 22 | + # Create the oneagent web app |
| 23 | + web_app_info = sdk.create_web_application_info(virtual_host, app_name, context_root) |
| 24 | + |
| 25 | + with web_app_info: |
| 26 | + # Attempt to extract the x-dynatrace header from the request |
| 27 | + dynatrace_header = request.headers.get("x-dynatrace") |
| 28 | + logger.debug("Bottle - tracing incoming request ({}) with header: {}".format(request.url, dynatrace_header)) |
| 29 | + tracer = sdk.trace_incoming_web_request(web_app_info, request.url, request.method, headers=request.headers, str_tag=dynatrace_header) |
| 30 | + tracer.start() |
| 31 | + setattr(request, "__dynatrace_tracer", tracer) |
| 32 | + except Exception as e: |
| 33 | + logger.warning("Bottle - failed to instrument request: {}".format(e)) |
| 34 | + |
| 35 | + @hook("after_request") |
| 36 | + def instrument_after_request(): |
| 37 | + try: |
| 38 | + # check if the request was instrumented |
| 39 | + tracer = getattr(request, "__dynatrace_tracer", None) |
| 40 | + if tracer: |
| 41 | + tracer.set_status_code(response.status_code) |
| 42 | + tracer.add_response_headers(response.headers) |
| 43 | + logger.debug("Bottle - ending incoming request ({}) with status: {}".format(request.url, response.status_code)) |
| 44 | + tracer.end() |
| 45 | + except Exception as e: |
| 46 | + logger.warning("Bottle - failed to instrument response: {}".format(e)) |
0 commit comments