Created
June 19, 2024 02:37
-
-
Save rajendrakumaryadav/c4475699dd968e3400acabe4bc9b0354 to your computer and use it in GitHub Desktop.
singleton_trace_provider
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from opentelemetry import trace | |
from opentelemetry.sdk.trace import TracerProvider | |
from opentelemetry.sdk.trace.export import BatchSpanExporter | |
class TracerSingleton: | |
""" | |
Singleton class to provide the OpenTelemetry tracer object. | |
""" | |
_instance = None | |
def __new__(cls): | |
""" | |
Ensures only one instance of the TracerSingleton is created. | |
""" | |
if not cls._instance: | |
cls._instance = super().__new__(cls) | |
cls._instance._tracer_provider = TracerProvider() | |
# Configure your span exporter here (e.g., Jaeger, Zipkin) | |
cls._instance._tracer_provider.add_span_exporter( | |
BatchSpanExporter(endpoint="http://localhost:9411/api/v2/spans") | |
) | |
return cls._instance | |
def get_tracer(self, instrument_name): | |
""" | |
Returns the OpenTelemetry tracer object. | |
""" | |
return trace.get_tracer(__name__, provider=self._tracer_provider) | |
# Example usage | |
tracer_singleton = TracerSingleton() | |
tracer = tracer_singleton.get_tracer("my_instrument") | |
# Use the tracer object for instrumentation | |
with tracer.start_as_current_span("my_operation_name"): | |
# Your application logic here | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment