리셋 되지 말자

Django Opentelemetry 연동 - 1 본문

Django

Django Opentelemetry 연동 - 1

kyeongjun-dev 2024. 1. 25. 23:58

django 실행

python 및 pip 버전

python --version
Python 3.10.8

pip --version
pip 22.2.2 from /home/ubuntu/Django/venv-test/lib/python3.10/site-packages/pip (python 3.10)

 

패키지 설치

pip install django
pip install opentelemetry-instrumentation
pip install opentelemetry-instrumentation-django
pip install opentelemetry-sdk
pip install opentelemetry-exporter-otlp

 

django 프로젝트 생성

django-admin startproject config .

ls
config  manage.py

 

runserver 동작 확인

python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
January 25, 2024 - 14:42:23
Django version 5.0.1, using settings 'config.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

 

Opentelemetry 적용

manage.py 코드 수정
- 수정 전

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()


- 수정 후

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys

from opentelemetry.instrumentation.django import DjangoInstrumentor

def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
    DjangoInstrumentor().instrument()
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()

 

config/wsgi.py 수정
- 수정 전

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')

application = get_wsgi_application()

 

- 수정 후 ( console span exporter 적용)

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')

application = get_wsgi_application()

from django.http import HttpResponse

from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import (
    BatchSpanProcessor,
    ConsoleSpanExporter,
)

trace.set_tracer_provider(TracerProvider())

trace.get_tracer_provider().add_span_processor(
    BatchSpanProcessor(ConsoleSpanExporter())
)

 

--noreload 옵션으로 runserver 실행

python manage.py runserver 0.0.0.0:8080 --noreload

 

localhost:8080 접속시, runserver를 실행한 콘솔창에서 otlp 로그 확인

[25/Jan/2024 14:56:28] "GET / HTTP/1.1" 200 10629
{
    "name": "GET",
    "context": {
        "trace_id": "0x41e326006d1c9eeb5fd4aeec4b5cee02",
        "span_id": "0xb8410e98c5b2b899",
        "trace_state": "[]"
    },
    "kind": "SpanKind.SERVER",
    "parent_id": null,
    "start_time": "2024-01-25T14:56:28.604748Z",
    "end_time": "2024-01-25T14:56:28.610056Z",
    "status": {
        "status_code": "UNSET"
    },
    "attributes": {
        "http.method": "GET",
        "http.server_name": ".localdomain",
        "http.scheme": "http",
        "net.host.port": 8080,
        "http.host": "localhost:8080",
        "http.url": "http://localhost:8080/",
        "net.peer.ip": "127.0.0.1",
        "http.user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
        "http.flavor": "1.1",
        "http.status_code": 200
    },
    "events": [],
    "links": [],
    "resource": {
        "attributes": {
            "telemetry.sdk.language": "python",
            "telemetry.sdk.name": "opentelemetry",
            "telemetry.sdk.version": "1.22.0",
            "service.name": "unknown_service"
        },
        "schema_url": ""
    }
}

'Django' 카테고리의 다른 글

Django Opentelemetry Tempo 연동 - 2  (0) 2024.01.26
나중에 공부할 내용(ORM)  (0) 2022.04.28
원격실습 환경 구성  (0) 2022.04.16
ORM  (0) 2022.04.16
CSRF 토큰 오류  (0) 2021.12.21
Comments