Opentelemetry 在Flask 產生span的時機點

less than 1 minute read

最近遇到一個問題,在Flask專案用OpenTelemetry,並且用了跟Flask的整合實作(opentelemetry-instrumentation-flask)。

在用span的時候遇到某些問題,所以無法拿到span,程式碼端看起來邏輯都沒問題,所以懷疑是lifecycle的問題,所以去trace implementation。

概念上,我們可以把opentelemetry-instrumentation-flask視為一個middleware,在invoke instrument_app的時候,會wrap wsgi_appbefore_requestafter request,程式碼如下:

app._original_wsgi_app = app.wsgi_app
app.wsgi_app = _rewrapped_app(
    app.wsgi_app,
    active_requests_counter,
    duration_histogram,
    response_hook,
    excluded_urls=excluded_urls,
)

tracer = trace.get_tracer(__name__, __version__, tracer_provider)

_before_request = _wrapped_before_request(
    request_hook,
    tracer,
    excluded_urls=excluded_urls,
    enable_commenter=enable_commenter,
    commenter_options=commenter_options
    if commenter_options
    else {},
)

app._before_request = _before_request
app.before_request(_before_request)

_teardown_request = _wrapped_teardown_request(
    excluded_urls=excluded_urls,
)
app._teardown_request = _teardown_request
app.teardown_request(_teardown_request)

基本上保持OpenTelemetry的基本概念,盡量對service transparent,不過這邊要注意在Flask url_value_preprocessor的時候,span還沒產生,那個時間點不視為request的一部分啊……

Updated: