anaconda_opentelemetry package

Submodules

anaconda_opentelemetry.attributes module

class anaconda_opentelemetry.attributes.ResourceAttributes(service_name: str, service_version: str, os_type: str = '', os_version: str = '', python_version: str = '', hostname: str = '', platform: str = '', environment: Literal['', 'test', 'development', 'staging', 'production'] = '', user_id: str = '')

Bases: object

Class used to configure common attributes on initialization and dynamic attributes thereafter

Parameters:
  • service_name (str) – name of client service. REQUIRED (enforced regex of ^[a-zA-Z0-9._-]{1,30}$), converted later to service.name

  • service_version (str) – version of client service. REQUIRED (enforced regex of ^[a-zA-Z0-9._-]{1,30}$), converted later to service.version

  • os_type (str) – operating system type of client machine

  • os_version (str) – operating system version of client machine

  • python_version (str) – python version of client the package

  • hostname (str) – hostname of client machine

  • platform (str) – infrastructure on which the software is provided

  • environment (Literal["", "test", "development", "staging", "production"]) – envrionment the software is running in

  • user_id (str) – some string denoting a user of a client application. This will not be stored in Resource Attributes and will be moved to attributes.

  • parameters (Dict[str, str]) – optional dictionary containing all other telemetry attributes a client would like to add

  • client_sdk_version (str) – version of package. READONLY

  • schema_version (str) – version of telemetry schema used by package. READONLY

parameters: dict
set_attributes(**kwargs) None

Sets attributes according to key value pairs passed to this function. Will overwrite existing attributes, unless they are readonly.

Note: Setting user_id via this method is maintained for backwards compatability. Doing so will override any user_ids set later in event specific attributes.

Parameters:

**kwargs – any keyword arguments. This can set named class properties (common attributes), or any other wildcard name (stored in parameters)

The following are the common attributes that can be set:

service_name (str): name of client service

service_version (str): version of client service

os_type (str): operating system type of client machine

os_version (str): operating system version of client machine

python_version (str): python version of client the package

hostname (str): hostname of client machine

platform (str): infrastructure on which the software runs

environment (Literal[“”, “test”, “development”, “staging”, “production”]): environment of the software

user_id (str): some string denoting a user of a client application

anaconda_opentelemetry.common module

Anaconda Telemetry - Common base class and exceptions for signal classes.

exception anaconda_opentelemetry.common.MetricsNotInitialized

Bases: RuntimeError

anaconda_opentelemetry.config module

Anaconda Telemetry - Configuration Module

This module provides the configuration setting from a file or a dictionary (or both)

class anaconda_opentelemetry.config.Configuration(default_endpoint: str = None, default_auth_token: str = None, default_private_ca_cert_file: str = None, config_dict: Dict[str, Any] = {})

Bases: object

Configuration class to supply settings for Anaconda Telemetry. For environment variables make these capitalized and prepend with ‘ATEL_’ and remove suffix ‘_NAME’. For example, the environment variable for the default endpoint would be ‘ATEL_DEFAULT_ENDPOINT’. The environment variable for the logging endpoint would be ‘ATEL_LOGGING_ENDPOINT’. The bool values can be represented by “1”, “yes”, “true” case-insensitive and all other values are considered False.

  • DEFAULT_ENDPOINT_NAME - Name for the default endpoint in the configuration files or dictionaries passed into this class.

  • LOGGING_ENDPOINT_NAME - Name for the logging endpoint in the configuration files or dictionaries passed into this class.

  • TRACING_ENDPOINT_NAME - Name for the tracing endpoint in the configuration files or dictionaries passed into this class.

  • METRICS_ENDPOINT_NAME - Name for the metrics endpoint in the configuration files or dictionaries passed into this class.

  • USE_CONSOLE_EXPORTER_NAME - Name for the console exporter flag in the configuration files or dictionaries passed into this class.

  • DEFAULT_AUTH_TOKEN_NAME - Name for the default authentication token in the configuration files or dictionaries passed into this class.

  • LOGGING_AUTH_TOKEN_NAME - Name for the logging authentication token in the configuration files or dictionaries passed into this class.

  • TRACING_AUTH_TOKEN_NAME - Name for the tracing authentication token in the configuration files or dictionaries passed into this class.

  • METRICS_AUTH_TOKEN_NAME - Name for the metrics authentication token in the configuration files or dictionaries passed into this class.

  • METRICS_EXPORT_INTERVAL_MS_NAME - Name for the metrics export interval in milliseconds in the configuration files or dictionaries passed into this class.

  • TRACING_EXPORT_INTERVAL_MS_NAME - Name for the tracing export interval in milliseconds in the configuration files or dictionaries passed into this class.

  • LOGGING_LEVEL_NAME - Name for the logging level in the configuration files or dictionaries passed into this class.

  • SESSION_ENTROPY_VALUE_NAME - Name for the session entropy value in the configuration files or dictionaries passed into this class.

  • TLS_PRIVATE_CA_CERT_FILE_NAME - File name for the TLS private CA certificate in the configuration files or dictionaries passed into this class.

  • SKIP_INTERNET_CHECK_NAME - If you are running in an environment that does not have access to the internet, set this to True.

  • USE_CUMULATIVE_METRICS_NAME - If aggregating data in the client is required for Counter, or Histogram set this to a True state.

To initializes the Configuration instance.

config = Configuration(default_endpoint=’example.com:4317’).set_auth_token(‘<token_here>’)

Parameters:
  • default_endpoint (str) – Default endpoint in the form ‘<IPv4|domain_name>:<port>’.

  • config_dict (Dict[str,Any], optional) – Optional dictionary containing configuration settings.

DEFAULT_AUTH_TOKEN_NAME = 'default_auth_token'
DEFAULT_CA_CERT_NAME = 'default_credentials'
LOGGING_AUTH_TOKEN_NAME = 'logging_auth_token'
LOGGING_CA_CERT_NAME = 'logging_credentials'
METRICS_AUTH_TOKEN_NAME = 'metrics_auth_token'
METRICS_CA_CERT_NAME = 'metrics_credentials'
TRACING_AUTH_TOKEN_NAME = 'tracing_auth_token'
TRACING_CA_CERT_NAME = 'tracing_credentials'
TRACING_EXPORT_INTERVAL_MS_NAME = 'tracing_export_interval_ms'
USE_CUMULATIVE_METRICS_NAME = 'use_cumulative_metrics'
set_auth_token(auth_token: str)

Sets the default authentication token for the endpoints (default endpoint). It is a fallback for all endpoints (default, logging, tracing, metrics). If passed in a dict in the constructor, use predefined name DEFAULT_AUTH_TOKEN_NAME.

Parameters:

auth_token (str) – Authentication token to be used with the endpoints.

Returns:

Self

set_auth_token_logging(auth_token: str)

Sets the authentication token for the logging endpoint. If passed in a dict in the constructor, use predefined name LOGGING_AUTH_TOKEN_NAME.

Parameters:

auth_token (str) – Authentication token to be used with the endpoints.

Returns:

Self

set_auth_token_metrics(auth_token: str)

Sets the authentication token for the metrics endpoint. If passed in a dict in the constructor, use predefined name METRICS_AUTH_TOKEN_NAME.

Parameters:

auth_token (str) – Authentication token to be used with the endpoints.

Returns:

Self

set_auth_token_tracing(auth_token: str)

Sets the authentication token for the tracing endpoint. If passed in a dict in the constructor, use predefined name TRACING_AUTH_TOKEN_NAME.

Parameters:

auth_token (str) – Authentication token to be used with the endpoints.

Returns:

Self

set_console_exporter(use_console: bool = True)

Sets whether to use console exporter for output. If passed in a dict in the constructor, use predefined name USE_CONSOLE_EXPORTER_NAME. It applies to all exporters (logging, tracing, metrics). This is a convenience used for testing only. Do not set in produiction. Also to set this value without modifying your code use the environment variable ‘OTEL_USE_CONSOLE_EXPORTER’. Set this to true, yes, or 1. Case doesn’t matter.

$ export OTEL_USE_CONSOLE_EXPORTER=TRUE

Parameters:

use_console (bool) – True to use console exporter, False otherwise.

Returns:

Self

set_logging_endpoint(endpoint: str, auth_token: str = None, cert_ca_file: str = None)

Sets the logging endpoint. Intended for usage prior to calling initialize_telemetry(). If this method is called after the initialize_telemetry() call, it will not work. The change_signal_endpoint must be used. If passed in a dict in the constructor, use predefined name LOGGING_ENDPOINT_NAME. If not set, the default endpoint will be used.

Parameters:
  • endpoint (str) – Logging endpoint in the form ‘<IPv4|domain_name>:<port>’.

  • auth_token (str) – Bearer auth token for the logging endpoint or None.

  • cert_ca_file (str) – Absolute file path to the private cert file for logging or None. Rarely used.

Returns:

Self

Raises:

ValueError – If the endpoint format is invalid.

set_logging_level(level: str)

Sets the logging level for the telemetry logging to the collector. The built-in Python logging module must be used or logging will not get sent to the server. If passed in a dict in the constructor, use predefined name LOGGING_LEVEL_NAME. This will not affect the logging level of the root logger, only what is sent to OTel.

Parameters:

level (str) – Logging level to be used. It can be ‘debug’, ‘info’, ‘warn’, ‘warning’, ‘error’, ‘fatal’ or ‘critical’. If not one of these strings, the logger level is not set.

Returns:

Self

set_metrics_endpoint(endpoint: str, auth_token: str = None, cert_ca_file: str = None)

Sets the metrics endpoint. Intended for usage prior to calling initialize_telemetry(). If this method is called after the initialize_telemetry() call, it will not work. The change_signal_endpoint must be used. If passed in a dict in the constructor, use predefined name METRICS_ENDPOINT_NAME. If not set, the default endpoint will be used.

Parameters:
  • endpoint (str) – Metrics endpoint in the form ‘<IPv4|domain_name>:<port>’.

  • auth_token (str) – Bearer auth token for the metrics endpoint or None.

  • cert_ca_file (str) – Absolute file path to the private cert file for metrics or None. Rarely used.

Returns:

Self

Raises:

ValueError – If the endpoint format is invalid.

set_metrics_export_interval_ms(interval_ms: int)

Sets the metrics export interval in milliseconds. If this value is not set, the default is 60,000 milliseconds (1 minute). If passed in a dict in the constructor, use predefined name METRICS_EXPORT_INTERVAL_NAME. This dictates how long the batching inside OpenTelemetry lasts before sending to the collector.

Parameters:
  • interval (int) – Interval in milliseconds for exporting metrics. If this is zero or

  • set. (negative then the export interval is not)

Returns:

Self

set_skip_internet_check(value: bool)

Sets whether to skip the internet check. This is useful for environments that do not have internet access. If passed in a dict in the constructor, use predefined name SKIP_INTERNET_CHECK_NAME.

Parameters:

value (bool) – True to skip the internet check, False otherwise.

Returns:

Self

set_tls_private_ca_cert(cert_file: str)

TLS certificate used for default endpoint only. Sets the actual TLS private CA certificate to be used for secure connections. This is used to verify the server’s certificate when using TLS. If passed in a dict in the constructor, use predefined name DEFAULT_CA_CERT_NAME. The caller must pass a file path that will later be utilized to find a cert. Can be used to set CA to None is cert_file is None.

Parameters:

cert_file (str) – File location of CA cert file intended for use

Returns:

Self

set_tls_private_ca_cert_logging(cert_file: str)

TLS certificate used for logging endpoint only. Sets the actual TLS private CA certificate to be used for secure connections. This is used to verify the server’s certificate when using TLS. If passed in a dict in the constructor, use predefined name LOGGING_CA_CERT_NAME. The caller must pass a file path that will later be utilized to find a cert. Can be used to set CA to None is cert_file is None.

Parameters:

cert_file (str) – File location of CA cert file intended for use

Returns:

Self

set_tls_private_ca_cert_metrics(cert_file: str)

TLS certificate used for metrics endpoint only. Sets the actual TLS private CA certificate to be used for secure connections. This is used to verify the server’s certificate when using TLS. If passed in a dict in the constructor, use predefined name METRICS_CA_CERT_NAME. The caller must pass a file path that will later be utilized to find a cert. Can be used to set CA to None is cert_file is None.

Parameters:

cert_file (str) – File location of CA cert file intended for use

Returns:

Self

set_tls_private_ca_cert_tracing(cert_file: str)

TLS certificate used for tracing endpoint only. Sets the actual TLS private CA certificate to be used for secure connections. This is used to verify the server’s certificate when using TLS. If passed in a dict in the constructor, use predefined name TRACING_CA_CERT_NAME. The caller must pass a file path that will later be utilized to find a cert. Can be used to set CA to None is cert_file is None.

Parameters:

cert_file (str) – File location of CA cert file intended for use

Returns:

Self

set_tracing_endpoint(endpoint: str, auth_token: str = None, cert_ca_file: str = None)

Sets the tracing endpoint. Intended for usage prior to calling initialize_telemetry(). If this method is called after the initialize_telemetry() call, it will not work. The change_signal_endpoint must be used. If passed in a dict in the constructor, use predefined name TRACING_ENDPOINT_NAME. If not set, the default endpoint is used.

Parameters:
  • endpoint (str) – Tracing endpoint in the form ‘<IPv4|domain_name>:<port>’.

  • auth_token (str) – Bearer auth token for the tracing endpoint or None.

  • cert_ca_file (str) – Absolute file path to the private cert file for tracing or None. Rarely used.

Returns:

Self

Raises:

ValueError – If the endpoint format is invalid.

set_tracing_export_interval_ms(interval_ms: int)

Sets the tracing export interval in milliseconds. If this value is not set, the default is 60,000 milliseconds (1 minute). If passed in a dict in the constructor, use predefined name TRACING_EXPORT_INTERVAL_NAME. This dictates how long the batching inside OpenTelemetry lasts before sending to the collector.

Parameters:
  • interval (int) – Interval in milliseconds for exporting metrics. If this is zero or

  • set. (negative then the export interval is not)

Returns:

Self

set_tracing_session_entropy(session_entropy)

Sets the session entropy for tracing. This is used to ensure that traces are unique across different sessions. If this value is not set, a default value will be used. If passed in a dict in the constructor, use predefined name SESSION_ENTROPY_VALUE_NAME.

Parameters:

session_entropy (Any) – Session entropy to be used for tracing.

Returns:

Self

set_use_cumulative_metrics(value: bool)

Sets the use of cumulative aggregation temporality if True. The default (False) is delta (not aggregated).

Cumulative counters report a measurement consistently for each export interval. The would result in “duplicate” metrics. To get metric readings only for the difference between the current count and the previous count, use delta aggregation.

Parameters:
  • value (bool) – True turns on cumulative aggregation, False (the default) is to send

  • deltas (no aggregation)

Returns:

Self

anaconda_opentelemetry.config.deprecated(func)

anaconda_opentelemetry.exporter_shim module

class anaconda_opentelemetry.exporter_shim.ExporterState(*values)

Bases: Enum

READY = 1
UPDATING = 2
class anaconda_opentelemetry.exporter_shim.OTLPLogExporterShim(exporter_class, **kwargs)

Bases: _OTLPExporterMixin, LogExporter

class anaconda_opentelemetry.exporter_shim.OTLPMetricExporterShim(exporter_class, **kwargs)

Bases: _OTLPExporterMixin, MetricExporter

class anaconda_opentelemetry.exporter_shim.OTLPSpanExporterShim(exporter_class, **kwargs)

Bases: _OTLPExporterMixin, SpanExporter

anaconda_opentelemetry.formatting module

anaconda_opentelemetry.logging module

Anaconda Telemetry - Logging signal class and EventLogger.

class anaconda_opentelemetry.logging.EventLogger(provider: LoggerProvider, logger_name: str = 'event_logger')

Bases: object

Emits log records purely as OTel log telemetry, bypassing Python’s logging hierarchy so they never appear in console/file handlers or interfere with developer log levels. Optional way to export logs, the Python logging module is supported as well.

anaconda_opentelemetry.metrics module

Anaconda Telemetry - Metrics signal class.

anaconda_opentelemetry.signals module

Anaconda Telemetry - Metrics Module

This module provides functionality for logging, metrics, and tracing (together called signals) using OpenTelemetry. It includes classes for handling logging, metrics, and tracing, as well as functions for initializing the telemetry system and recording metrics.

anaconda_opentelemetry.signals.change_signal_endpoint(signal_type: str, new_endpoint: str, auth_token: str = None)

Updates the endpoint for the passed signal

Parameters:

signal_type (str) – signal type to update endpoint for. Supported values are ‘logging’, ‘metrics’, and ‘tracing’

Returns:

value indicating whether the update was successful or not

Return type:

boolean

anaconda_opentelemetry.signals.decrement_counter(counter_name, by=1, attributes: Dict[str, str | bool | int | float | Sequence[str | bool | int | float]] = {}) bool

Decrements a up down counter with the given name and value. If applied to a regular counter it will log a warning and silently fail.

Will catch any exceptions generated by metric usage.

Parameters:
  • counter_name (str) – The name of the counter.

  • by (int, optional) – The value to decrement by. Defaults to 1. abs(by) is used to protect from negative numbers.

  • attributes (dict, optional) – Additional attributes for the counter. Defaults to {}.

Returns:

True if the counter was decremented successfully, False otherwise (logging the error).

Return type:

bool

anaconda_opentelemetry.signals.get_telemetry_logger_handler() LoggingHandler

Returns the telemetry logger handler. This lets the package user control how the application uses the telemetry logger. Insert this handler into your named logger.

log = logging.getLogger(“my_logger”) log.addHandler(get_telemetry_logger_handler())

Previously, this was injected into the root logger, but this turned out to be problematic for some applications that wanted to control the logging configuration more precisely. This injection behavior is now disabled. If you wish to inject the handler into the root logger, you can do so manually. See the Python logging documentation for more information.

Returns:

The telemetry logger handler if logging was enabled via signal_types in initialize_telemetry, otherwise this function returns None.

Return type:

logging.Logger

Raises:

RuntimeError – if initialize_telemetry has not been called

anaconda_opentelemetry.signals.get_trace(name: str, attributes: Dict[str, str | bool | int | float | Sequence[str | bool | int | float]] = {}, carrier: Dict[str, str] = None) Iterator[_ASpan]

Create or continue a named trace (based on the ‘carrier’ parameter).

Use the function like a Python I/O object (keyword ‘with’) to ensure the span is closed properly.

Will catch any exceptions generated by tracing usage.

Parameters:
  • name (str) – The name of the trace.

  • attributes (dict, optional) – Additional attributes for the trace. Defaults to {}.

  • carrier (dict, optional) – The carrier used to continue a trace context in the output data. Defaults to None.

Example

with get_trace(“my_trace_name”, {“key”: “value”}) as span:

# Do some work here pass # The span will be closed automatically when exiting the ‘with’ block.

Returns:

An iterator for the tracer.

Return type:

Iterator[Tracer]

anaconda_opentelemetry.signals.increment_counter(counter_name, by=1, attributes: Dict[str, str | bool | int | float | Sequence[str | bool | int | float]] = {}) bool

Increments a counter or up down counter by the given parameter ‘by’.

Will catch any exceptions generated by metric usage.

Parameters:
  • counter_name (str) – The name of the counter.

  • by (int, optional) – The value to increment by. Defaults to 1. The abs(by) is used to protect from negative numbers.

  • attributes (dict, optional) – Additional attributes for the counter. Defaults to {}.

Returns:

True if the counter was incremented successfully, False otherwise (logging the error).

Return type:

bool

anaconda_opentelemetry.signals.initialize_telemetry(config: Configuration, attributes: ResourceAttributes = None, signal_types: List[str] = ['metrics'])

Initializes the telemetry system.

Parameters:
  • service_name (str) – The name of the service.

  • service_version (str) – The version of the service.

  • config (Configuration) – The configuration for the telemetry. At a minimum, the Configuration must have a default endpoint for connection to the collector.

  • attributes (ResourceAttributes, optional) – A class containing common attributes. If provided, it will override any values shared with configuration file.

  • signal_types (list, optional) – List of metric types to initialize. Defaults to [‘logging’,’metrics’,’tracing’]. Supported values are ‘logging’, ‘metrics’, and ‘tracing’. If an empty list is provided, no metrics will be initialized.

Raises:

ValueError – If the config passed is None or the attributes passed are None.

anaconda_opentelemetry.signals.record_histogram(metric_name, value, attributes: Dict[str, str | bool | int | float | Sequence[str | bool | int | float]] = {}) bool

Records a increasing only metric with the given name and value. The value will always appear in the attributes section in the raw OTLP output and the timestamp will be the histogram value.

Will catch any exceptions generated by metric usage.

Parameters:
  • metric_name (str) – The name of the metric.

  • value (float) – The value of the metric. Can be any float since the timestamp is the ever increasing value of the histogram.

  • attributes (dict, optional) – Additional attributes for the metric. Defaults to {}.

Returns:

True if the metric was recorded successfully, False otherwise (logging the error).

Return type:

bool

anaconda_opentelemetry.signals.send_event(body: str, event_name: str, attributes: Dict[str, str | bool | int | float | Sequence[str | bool | int | float]] = {}) bool

Sends a log event directly to the OpenTelemetry pipeline without using Python’s logging module. This is useful when you want to export log telemetry but don’t want the output mixing with your application’s output or developer logs.

Params:

body (str): the log message body event_name (str): mandatory event name added to attributes attributes (AttrDict): optional attributes dict

Returns:

True if the event was sent, False if logging was not initialized

Return type:

bool

Raises:

RuntimeError – if initialize_telemetry has not been called

anaconda_opentelemetry.tracing module

Anaconda Telemetry - Tracing signal class and span classes.

class anaconda_opentelemetry.tracing.ASpan

Bases: ABC

Abstract base class for a span in the tracing system. This class should not be instantiated directly. Use the get_trace function to create an instance of this class.

add_attributes(attributes: Dict[str, str | bool | int | float | Sequence[str | bool | int | float]]) None

Adds attributes for the span (adds to the orginal attribute on creation of the span).

Parameters:

attributes (dict) – A dictionary of attributes to add for the span.

add_event(name: str, attributes: Dict[str, str | bool | int | float | Sequence[str | bool | int | float]] = None) None

Add an event to the span with the given name and attributes.

Parameters:
  • name (str) – The name of the event.

  • attributes (dict, optional) – Additional attributes for the event. Defaults to None.

add_exception(exception: Exception) None

Add an exception to the span. If the exception is None, a generic exception is recorded.

Parameters:

exception (Exception) – The exception to add to the span.

set_error_status(msg: str | None = None) None

Set the status of the span to ERROR. This indicates that an error occurred during the span’s execution.

Parameters:

msg (str, optional) – An optional message to include in the error status. Defaults to None.

Module contents