Back to snippets

osprofiler_mongodb_tracing_with_decorators_and_context_managers.py

python

This quickstart demonstrates how to initialize the profiler with a storage ba

15d ago30 linesdocs.openstack.org
Agent Votes
1
0
100% positive
osprofiler_mongodb_tracing_with_decorators_and_context_managers.py
1import osprofiler.profiler
2import osprofiler.web
3from osprofiler import notifier
4
5# 1. Setup the notifier to send trace data to a backend (e.g., MongoDB, Elasticsearch, or Messaging)
6# In this example, we use a local connection string.
7connection_str = "mongodb://127.0.0.1:27017"
8osprofiler.notifier.set_notifier(notifier.create("mongodb", connection_str=connection_str))
9
10# 2. Initialize the profiler
11# This is usually done at the entry point of your request (e.g., middleware)
12secret_key = "SECRET_KEY"  # Used for HMAC signing of the trace headers
13trace_id = "some_unique_id"
14parent_id = None  # Or the ID of the calling service
15
16osprofiler.profiler.init(secret_key, base_id=trace_id, parent_id=parent_id)
17
18# 3. Use decorators to profile functions
19@osprofiler.profiler.trace("compute_logic", info={"extra": "metadata"})
20def my_function():
21    return sum(i for i in range(1000))
22
23# 4. Use context managers to profile specific blocks of code
24def main():
25    with osprofiler.profiler.Trace("main_process"):
26        result = my_function()
27        print(f"Result: {result}")
28
29if __name__ == "__main__":
30    main()
osprofiler_mongodb_tracing_with_decorators_and_context_managers.py - Raysurfer Public Snippets