Skip to content

Commit

Permalink
Merge pull request #33 from odigos-io/silence-urllib3-logs
Browse files Browse the repository at this point in the history
Silence urllib3 logs
  • Loading branch information
tamirdavid1 committed Sep 24, 2024
2 parents d7cda38 + b687ff1 commit a92cf53
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 44 deletions.
21 changes: 21 additions & 0 deletions initializer/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import logging


# This is the main odigos-opentelemetry-python logger setup function.
# It is used by all modules within this package to ensure that all logs are captured by the same logger.
def setup_logging():
odigos_logger = logging.getLogger('odigos')
odigos_logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
odigos_logger.addHandler(handler)

odigos_logger.propagate = False # Prevent logs from reaching the root logger
odigos_logger.disabled = True # Comment to enable the logger

# Suppress third-party loggers used by odigos-opentelemetry-python (before they are used)
logging.getLogger('urllib3_odigos').setLevel(logging.CRITICAL)
logging.getLogger('requests_odigos').setLevel(logging.CRITICAL)

setup_logging()
17 changes: 9 additions & 8 deletions initializer/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@


MINIMUM_PYTHON_SUPPORTED_VERSION = (3, 8)

def initialize_components(trace_exporters = None, metric_exporters = None, log_exporters = None , span_processor = None):
resource_attributes_event = threading.Event()
client = None
Expand All @@ -37,7 +37,6 @@ def initialize_components(trace_exporters = None, metric_exporters = None, log_e
received_value = client.resource_attributes

if received_value:

auto_resource = {
"telemetry.distro.name": "odigos",
"telemetry.distro.version": VERSION,
Expand All @@ -50,19 +49,21 @@ def initialize_components(trace_exporters = None, metric_exporters = None, log_e
.merge(ProcessResourceDetector().detect())

odigos_sampler = initialize_traces_if_enabled(trace_exporters, resource, span_processor)

client.sampler = odigos_sampler

initialize_metrics_if_enabled(metric_exporters, resource)
initialize_logging_if_enabled(log_exporters, resource)

# # Reload distro modules to ensure the new path is used.
reload_distro_modules()
else:
raise Exception("Did not receive resource attributes from the OpAMP server.")

except Exception as e:
if client is not None:
client.shutdown(custom_failure_message=str(e))

raise

finally:
# Make sure the distro modules are reloaded even if an exception is raised.
reload_distro_modules()

def initialize_traces_if_enabled(trace_exporters, resource, span_processor = None):
traces_enabled = os.getenv(sdk_config.OTEL_TRACES_EXPORTER, "none").strip().lower()
Expand Down
14 changes: 1 addition & 13 deletions initializer/odigos_sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,7 @@
import logging

# Setup the Sampler logger
sampler_logger = logging.getLogger(__name__)
sampler_logger.setLevel(logging.DEBUG)
sampler_logger.propagate = False # Prevent the log messages from being propagated to the root logger
sampler_logger.disabled = True # Comment this line to enable the logger

# Safely remove all attached handlers from the logger.
# This ensures that any existing handlers, if present, are detached,
# preventing them from processing or outputting any log messages.
for handler in sampler_logger.handlers[:]:
try:
sampler_logger.removeHandler(handler)
except Exception:
pass
sampler_logger = logging.getLogger('odigos')

class OdigosSampler(Sampler):

Expand Down
44 changes: 21 additions & 23 deletions opamp/http_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,7 @@
from opamp.health_status import AgentHealthStatus

# Setup the logger
opamp_logger = logging.getLogger(__name__)
opamp_logger.setLevel(logging.DEBUG)
opamp_logger.propagate = False # Prevent the log messages from being propagated to the root logger
opamp_logger.disabled = True # Comment this line to enable the logger

# Safely remove all attached handlers from the logger.
# This ensures that any existing handlers, if present, are detached,
# preventing them from processing or outputting any log messages.
for handler in opamp_logger.handlers[:]:
try:
opamp_logger.removeHandler(handler)
except Exception:
pass
opamp_logger = logging.getLogger('odigos')

class OpAMPHTTPClient:
def __init__(self, event, condition: threading.Condition):
Expand Down Expand Up @@ -110,28 +98,38 @@ def send_unsupported_version_disconnect_message(self, error_message: str) -> Non
def send_first_message_with_retry(self) -> None:
max_retries = 5
delay = 2

for attempt in range(1, max_retries + 1):
try:
# Send first message to OpAMP server, Health is false as the component is not initialized
agent_health = self.get_agent_health(component_health=False, last_error="Python OpenTelemetry agent is starting", status=AgentHealthStatus.STARTING.value)
agent_description = self.get_agent_description()
first_message_server_to_agent = self.send_agent_to_server_message(opamp_pb2.AgentToServer(agent_description=agent_description, health=agent_health))

self.update_remote_config_status(first_message_server_to_agent)
self.resource_attributes = utils.parse_first_message_to_resource_attributes(first_message_server_to_agent, opamp_logger)

# Send healthy message to OpAMP server
# opamp_logger.info("Reporting healthy to OpAMP server...")
agent_health = self.get_agent_health(component_health=True, status=AgentHealthStatus.HEALTHY.value)
self.send_agent_to_server_message(opamp_pb2.AgentToServer(health=agent_health))

break
# Check if the response of the first message is empty
# It may happen if OpAMPServer is not available
if first_message_server_to_agent.ListFields():
self.update_remote_config_status(first_message_server_to_agent)
self.resource_attributes = utils.parse_first_message_to_resource_attributes(first_message_server_to_agent, opamp_logger)

# Send healthy message to OpAMP server
# opamp_logger.info("Reporting healthy to OpAMP server...")
agent_health = self.get_agent_health(component_health=True, status=AgentHealthStatus.HEALTHY.value)
self.send_agent_to_server_message(opamp_pb2.AgentToServer(health=agent_health))

# Return if the first message was successfully sent
return

except Exception as e:
# opamp_logger.error(f"Error sending full state to OpAMP server: {e}")
# opamp_logger.error(f"Attempt {attempt}/{max_retries} failed. Error sending full state to OpAMP server: {e}")
pass

if attempt < max_retries:
time.sleep(delay)

# If all attempts failed, raise exception before starting the worker
raise Exception(f"Error sending first message to OpAMP server after {max_retries} attempts")


def worker(self):
while self.running:
Expand Down

0 comments on commit a92cf53

Please sign in to comment.