Skip to content

Commit

Permalink
Merge pull request #34 from odigos-io/do-not-instrument-django-withou…
Browse files Browse the repository at this point in the history
…t-setting-module-configured

feat: handle django without DJANGO_SETTINGS_MODULE
  • Loading branch information
tamirdavid1 authored Oct 1, 2024
2 parents a92cf53 + 4d7980c commit 2273334
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
5 changes: 4 additions & 1 deletion initializer/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.trace import set_tracer_provider

from .lib_handling import reorder_python_path, reload_distro_modules
from .lib_handling import reorder_python_path, reload_distro_modules, handle_django_instrumentation
from .version import VERSION

from .odigos_sampler import OdigosSampler
Expand All @@ -37,6 +37,9 @@ def initialize_components(trace_exporters = None, metric_exporters = None, log_e
received_value = client.resource_attributes

if received_value:

handle_django_instrumentation()

auto_resource = {
"telemetry.distro.name": "odigos",
"telemetry.distro.version": VERSION,
Expand Down
29 changes: 29 additions & 0 deletions initializer/lib_handling.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import sys
import importlib
import os
from opentelemetry.instrumentation.django.environment_variables import (
OTEL_PYTHON_DJANGO_INSTRUMENT,
)

def reorder_python_path():
paths_to_move = [path for path in sys.path if path.startswith('/var/odigos/')]
Expand Down Expand Up @@ -39,3 +44,27 @@ def reload_distro_modules() -> None:

if any(module.startswith(prefix) for prefix in needed_module_prefixes):
del sys.modules[module]



### Django

# Disables Django instrumentation if DJANGO_SETTINGS_MODULE is unset and adds the current directory to sys.path for proper Django instrumentation.
# These changes address this issue: https://github.com/open-telemetry/opentelemetry-python-contrib/issues/2495.
# TODO: Remove once the bug is fixed.
def handle_django_instrumentation():
if os.getenv('DJANGO_SETTINGS_MODULE', None) is None:
os.environ.setdefault(OTEL_PYTHON_DJANGO_INSTRUMENT, 'False')

else:
cwd_path = os.getcwd()
if cwd_path not in sys.path:
sys.path.insert(0, cwd_path)

# As an additional safeguard, we're ensuring that DJANGO_SETTINGS_MODULE is importable.
# This is done to prevent instrumentation from being enabled if the Django settings module cannot be imported.
try:
importlib.import_module('DJANGO_SETTINGS_MODULE')
except:
os.environ.setdefault(OTEL_PYTHON_DJANGO_INSTRUMENT, 'False')

0 comments on commit 2273334

Please sign in to comment.