您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ext_otel.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. import atexit
  2. import contextlib
  3. import logging
  4. import os
  5. import platform
  6. import socket
  7. import sys
  8. from typing import Union
  9. import flask
  10. from celery.signals import worker_init
  11. from flask_login import user_loaded_from_request, user_logged_in # type: ignore
  12. from configs import dify_config
  13. from dify_app import DifyApp
  14. from libs.helper import extract_tenant_id
  15. from models import Account, EndUser
  16. @user_logged_in.connect
  17. @user_loaded_from_request.connect
  18. def on_user_loaded(_sender, user: Union["Account", "EndUser"]):
  19. if dify_config.ENABLE_OTEL:
  20. from opentelemetry.trace import get_current_span
  21. if user:
  22. try:
  23. current_span = get_current_span()
  24. tenant_id = extract_tenant_id(user)
  25. if not tenant_id:
  26. return
  27. if current_span:
  28. current_span.set_attribute("service.tenant.id", tenant_id)
  29. current_span.set_attribute("service.user.id", user.id)
  30. except Exception:
  31. logging.exception("Error setting tenant and user attributes")
  32. pass
  33. def init_app(app: DifyApp):
  34. from opentelemetry.semconv.trace import SpanAttributes
  35. def is_celery_worker():
  36. return "celery" in sys.argv[0].lower()
  37. def instrument_exception_logging():
  38. exception_handler = ExceptionLoggingHandler()
  39. logging.getLogger().addHandler(exception_handler)
  40. def init_flask_instrumentor(app: DifyApp):
  41. meter = get_meter("http_metrics", version=dify_config.project.version)
  42. _http_response_counter = meter.create_counter(
  43. "http.server.response.count",
  44. description="Total number of HTTP responses by status code, method and target",
  45. unit="{response}",
  46. )
  47. def response_hook(span: Span, status: str, response_headers: list):
  48. if span and span.is_recording():
  49. try:
  50. if status.startswith("2"):
  51. span.set_status(StatusCode.OK)
  52. else:
  53. span.set_status(StatusCode.ERROR, status)
  54. status = status.split(" ")[0]
  55. status_code = int(status)
  56. status_class = f"{status_code // 100}xx"
  57. attributes: dict[str, str | int] = {"status_code": status_code, "status_class": status_class}
  58. request = flask.request
  59. if request and request.url_rule:
  60. attributes[SpanAttributes.HTTP_TARGET] = str(request.url_rule.rule)
  61. if request and request.method:
  62. attributes[SpanAttributes.HTTP_METHOD] = str(request.method)
  63. _http_response_counter.add(1, attributes)
  64. except Exception:
  65. logging.exception("Error setting status and attributes")
  66. pass
  67. instrumentor = FlaskInstrumentor()
  68. if dify_config.DEBUG:
  69. logging.info("Initializing Flask instrumentor")
  70. instrumentor.instrument_app(app, response_hook=response_hook)
  71. def init_sqlalchemy_instrumentor(app: DifyApp):
  72. with app.app_context():
  73. engines = list(app.extensions["sqlalchemy"].engines.values())
  74. SQLAlchemyInstrumentor().instrument(enable_commenter=True, engines=engines)
  75. def setup_context_propagation():
  76. # Configure propagators
  77. set_global_textmap(
  78. CompositePropagator(
  79. [
  80. TraceContextTextMapPropagator(), # W3C trace context
  81. B3Format(), # B3 propagation (used by many systems)
  82. ]
  83. )
  84. )
  85. def shutdown_tracer():
  86. provider = trace.get_tracer_provider()
  87. if hasattr(provider, "force_flush"):
  88. provider.force_flush()
  89. class ExceptionLoggingHandler(logging.Handler):
  90. """Custom logging handler that creates spans for logging.exception() calls"""
  91. def emit(self, record: logging.LogRecord):
  92. with contextlib.suppress(Exception):
  93. if record.exc_info:
  94. tracer = get_tracer_provider().get_tracer("dify.exception.logging")
  95. with tracer.start_as_current_span(
  96. "log.exception",
  97. attributes={
  98. "log.level": record.levelname,
  99. "log.message": record.getMessage(),
  100. "log.logger": record.name,
  101. "log.file.path": record.pathname,
  102. "log.file.line": record.lineno,
  103. },
  104. ) as span:
  105. span.set_status(StatusCode.ERROR)
  106. if record.exc_info[1]:
  107. span.record_exception(record.exc_info[1])
  108. span.set_attribute("exception.message", str(record.exc_info[1]))
  109. if record.exc_info[0]:
  110. span.set_attribute("exception.type", record.exc_info[0].__name__)
  111. from opentelemetry import trace
  112. from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter as GRPCMetricExporter
  113. from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter as GRPCSpanExporter
  114. from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter as HTTPMetricExporter
  115. from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter as HTTPSpanExporter
  116. from opentelemetry.instrumentation.celery import CeleryInstrumentor
  117. from opentelemetry.instrumentation.flask import FlaskInstrumentor
  118. from opentelemetry.instrumentation.redis import RedisInstrumentor
  119. from opentelemetry.instrumentation.requests import RequestsInstrumentor
  120. from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
  121. from opentelemetry.metrics import get_meter, get_meter_provider, set_meter_provider
  122. from opentelemetry.propagate import set_global_textmap
  123. from opentelemetry.propagators.b3 import B3Format
  124. from opentelemetry.propagators.composite import CompositePropagator
  125. from opentelemetry.sdk.metrics import MeterProvider
  126. from opentelemetry.sdk.metrics.export import ConsoleMetricExporter, PeriodicExportingMetricReader
  127. from opentelemetry.sdk.resources import Resource
  128. from opentelemetry.sdk.trace import TracerProvider
  129. from opentelemetry.sdk.trace.export import (
  130. BatchSpanProcessor,
  131. ConsoleSpanExporter,
  132. )
  133. from opentelemetry.sdk.trace.sampling import ParentBasedTraceIdRatio
  134. from opentelemetry.semconv.resource import ResourceAttributes
  135. from opentelemetry.trace import Span, get_tracer_provider, set_tracer_provider
  136. from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
  137. from opentelemetry.trace.status import StatusCode
  138. setup_context_propagation()
  139. # Initialize OpenTelemetry
  140. # Follow Semantic Convertions 1.32.0 to define resource attributes
  141. resource = Resource(
  142. attributes={
  143. ResourceAttributes.SERVICE_NAME: dify_config.APPLICATION_NAME,
  144. ResourceAttributes.SERVICE_VERSION: f"dify-{dify_config.project.version}-{dify_config.COMMIT_SHA}",
  145. ResourceAttributes.PROCESS_PID: os.getpid(),
  146. ResourceAttributes.DEPLOYMENT_ENVIRONMENT: f"{dify_config.DEPLOY_ENV}-{dify_config.EDITION}",
  147. ResourceAttributes.HOST_NAME: socket.gethostname(),
  148. ResourceAttributes.HOST_ARCH: platform.machine(),
  149. "custom.deployment.git_commit": dify_config.COMMIT_SHA,
  150. ResourceAttributes.HOST_ID: platform.node(),
  151. ResourceAttributes.OS_TYPE: platform.system().lower(),
  152. ResourceAttributes.OS_DESCRIPTION: platform.platform(),
  153. ResourceAttributes.OS_VERSION: platform.version(),
  154. }
  155. )
  156. sampler = ParentBasedTraceIdRatio(dify_config.OTEL_SAMPLING_RATE)
  157. provider = TracerProvider(resource=resource, sampler=sampler)
  158. set_tracer_provider(provider)
  159. exporter: Union[GRPCSpanExporter, HTTPSpanExporter, ConsoleSpanExporter]
  160. metric_exporter: Union[GRPCMetricExporter, HTTPMetricExporter, ConsoleMetricExporter]
  161. protocol = (dify_config.OTEL_EXPORTER_OTLP_PROTOCOL or "").lower()
  162. if dify_config.OTEL_EXPORTER_TYPE == "otlp":
  163. if protocol == "grpc":
  164. exporter = GRPCSpanExporter(
  165. endpoint=dify_config.OTLP_BASE_ENDPOINT,
  166. # Header field names must consist of lowercase letters, check RFC7540
  167. headers=(("authorization", f"Bearer {dify_config.OTLP_API_KEY}"),),
  168. insecure=True,
  169. )
  170. metric_exporter = GRPCMetricExporter(
  171. endpoint=dify_config.OTLP_BASE_ENDPOINT,
  172. headers=(("authorization", f"Bearer {dify_config.OTLP_API_KEY}"),),
  173. insecure=True,
  174. )
  175. else:
  176. headers = {"Authorization": f"Bearer {dify_config.OTLP_API_KEY}"} if dify_config.OTLP_API_KEY else None
  177. trace_endpoint = dify_config.OTLP_TRACE_ENDPOINT
  178. if not trace_endpoint:
  179. trace_endpoint = dify_config.OTLP_BASE_ENDPOINT + "/v1/traces"
  180. exporter = HTTPSpanExporter(
  181. endpoint=trace_endpoint,
  182. headers=headers,
  183. )
  184. metric_endpoint = dify_config.OTLP_METRIC_ENDPOINT
  185. if not metric_endpoint:
  186. metric_endpoint = dify_config.OTLP_BASE_ENDPOINT + "/v1/metrics"
  187. metric_exporter = HTTPMetricExporter(
  188. endpoint=metric_endpoint,
  189. headers=headers,
  190. )
  191. else:
  192. exporter = ConsoleSpanExporter()
  193. metric_exporter = ConsoleMetricExporter()
  194. provider.add_span_processor(
  195. BatchSpanProcessor(
  196. exporter,
  197. max_queue_size=dify_config.OTEL_MAX_QUEUE_SIZE,
  198. schedule_delay_millis=dify_config.OTEL_BATCH_EXPORT_SCHEDULE_DELAY,
  199. max_export_batch_size=dify_config.OTEL_MAX_EXPORT_BATCH_SIZE,
  200. export_timeout_millis=dify_config.OTEL_BATCH_EXPORT_TIMEOUT,
  201. )
  202. )
  203. reader = PeriodicExportingMetricReader(
  204. metric_exporter,
  205. export_interval_millis=dify_config.OTEL_METRIC_EXPORT_INTERVAL,
  206. export_timeout_millis=dify_config.OTEL_METRIC_EXPORT_TIMEOUT,
  207. )
  208. set_meter_provider(MeterProvider(resource=resource, metric_readers=[reader]))
  209. if not is_celery_worker():
  210. init_flask_instrumentor(app)
  211. CeleryInstrumentor(tracer_provider=get_tracer_provider(), meter_provider=get_meter_provider()).instrument()
  212. instrument_exception_logging()
  213. init_sqlalchemy_instrumentor(app)
  214. RedisInstrumentor().instrument()
  215. RequestsInstrumentor().instrument()
  216. atexit.register(shutdown_tracer)
  217. def is_enabled():
  218. return dify_config.ENABLE_OTEL
  219. @worker_init.connect(weak=False)
  220. def init_celery_worker(*args, **kwargs):
  221. if dify_config.ENABLE_OTEL:
  222. from opentelemetry.instrumentation.celery import CeleryInstrumentor
  223. from opentelemetry.metrics import get_meter_provider
  224. from opentelemetry.trace import get_tracer_provider
  225. tracer_provider = get_tracer_provider()
  226. metric_provider = get_meter_provider()
  227. if dify_config.DEBUG:
  228. logging.info("Initializing OpenTelemetry for Celery worker")
  229. CeleryInstrumentor(tracer_provider=tracer_provider, meter_provider=metric_provider).instrument()