Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

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