sycommon-python-lib 0.1.21__py3-none-any.whl → 0.1.46__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,6 +3,7 @@ from sqlalchemy import create_engine, text
3
3
  from sycommon.config.Config import SingletonMeta
4
4
  from sycommon.config.DatabaseConfig import DatabaseConfig, convert_dict_keys
5
5
  from sycommon.logging.kafka_log import SYLogger
6
+ from sycommon.logging.sql_logger import SQLTraceLogger
6
7
  from sycommon.synacos.nacos_service import NacosService
7
8
 
8
9
 
@@ -62,9 +63,13 @@ class DatabaseConnector(metaclass=SingletonMeta):
62
63
  max_overflow=20, # 最大溢出连接数
63
64
  pool_timeout=30, # 连接超时时间(秒)
64
65
  pool_recycle=3600, # 连接回收时间(秒)
65
- pool_pre_ping=True # 每次获取连接前检查连接是否有效
66
+ pool_pre_ping=True, # 每次获取连接前检查连接是否有效
67
+ echo=False, # 打印 SQL 语句
66
68
  )
67
69
 
70
+ # 注册 SQL 日志拦截器
71
+ SQLTraceLogger.setup_sql_logging(self.engine)
72
+
68
73
  # 测试
69
74
  if not self.test_connection():
70
75
  raise Exception("Database connection test failed")
@@ -173,7 +173,7 @@ class KafkaLogger(metaclass=SingletonMeta):
173
173
  "className": "",
174
174
  "sqlCost": 0,
175
175
  "size": len(str(message)),
176
- "uid": int(trace_id) if trace_id and trace_id.isdigit() else 0
176
+ "uid": int(Snowflake.next_id()) # 独立新的id
177
177
  }
178
178
 
179
179
  # 智能队列管理
@@ -470,12 +470,22 @@ class SYLogger:
470
470
  thread_info = SYLogger._get_execution_context()
471
471
 
472
472
  # 构建日志结构,添加线程/协程信息到threadName字段
473
- request_log = {
474
- "trace_id": str(trace_id) if trace_id else Snowflake.next_id(),
475
- "message": msg_str,
476
- "level": level,
477
- "threadName": thread_info
478
- }
473
+ request_log = {}
474
+ if level == "ERROR":
475
+ request_log = {
476
+ "trace_id": str(trace_id) if trace_id else Snowflake.next_id(),
477
+ "message": msg_str,
478
+ "traceback": traceback.format_exc(),
479
+ "level": level,
480
+ "threadName": thread_info
481
+ }
482
+ else:
483
+ request_log = {
484
+ "trace_id": str(trace_id) if trace_id else Snowflake.next_id(),
485
+ "message": msg_str,
486
+ "level": level,
487
+ "threadName": thread_info
488
+ }
479
489
 
480
490
  # 选择日志级别
481
491
  _log = ''
@@ -490,7 +500,7 @@ class SYLogger:
490
500
  logger.info(_log)
491
501
 
492
502
  if os.getenv('DEV-LOG', 'false').lower() == 'true':
493
- pprint(_log)
503
+ pprint.pprint(_log)
494
504
 
495
505
  @staticmethod
496
506
  def info(msg: any, *args, **kwargs):
@@ -0,0 +1,53 @@
1
+ from sqlalchemy import event
2
+ from sqlalchemy.engine import Engine
3
+ from sycommon.logging.kafka_log import SYLogger
4
+ import time
5
+ from datetime import datetime
6
+ from decimal import Decimal
7
+
8
+
9
+ class SQLTraceLogger:
10
+ @staticmethod
11
+ def setup_sql_logging(engine: Engine):
12
+ """为 SQLAlchemy 引擎注册事件监听器"""
13
+ def serialize_params(params):
14
+ """处理特殊类型参数的序列化"""
15
+ if isinstance(params, (list, tuple)):
16
+ return [serialize_params(p) for p in params]
17
+ elif isinstance(params, dict):
18
+ return {k: serialize_params(v) for k, v in params.items()}
19
+ elif isinstance(params, datetime):
20
+ return params.isoformat()
21
+ elif isinstance(params, Decimal):
22
+ return float(params)
23
+ else:
24
+ return params
25
+
26
+ @event.listens_for(Engine, "after_cursor_execute")
27
+ def after_cursor_execute(
28
+ conn, cursor, statement, parameters, context, executemany
29
+ ):
30
+ try:
31
+ start_time = conn._execution_options.get(
32
+ "_start_time", time.time())
33
+ execution_time = (time.time() - start_time) * 1000
34
+
35
+ sql_log = {
36
+ "type": "SQL",
37
+ "statement": statement,
38
+ "parameters": serialize_params(parameters),
39
+ "execution_time_ms": round(execution_time, 2),
40
+ }
41
+
42
+ SYLogger.info(f"SQL执行: {sql_log}")
43
+ except Exception as e:
44
+ SYLogger.error(f"SQL日志处理失败: {str(e)}")
45
+
46
+ @event.listens_for(Engine, "before_cursor_execute")
47
+ def before_cursor_execute(
48
+ conn, cursor, statement, parameters, context, executemany
49
+ ):
50
+ try:
51
+ conn = conn.execution_options(_start_time=time.time())
52
+ except Exception as e:
53
+ SYLogger.error(f"SQL开始时间记录失败: {str(e)}")
@@ -1,4 +1,4 @@
1
- from src.sycommon.health.metrics import setup_metrics_handler
1
+ from sycommon.health.metrics import setup_metrics_handler
2
2
  from sycommon.health.ping import setup_ping_handler
3
3
  from sycommon.middleware.cors import setup_cors_handler
4
4
  from sycommon.middleware.docs import setup_docs_handler
@@ -79,7 +79,7 @@ def setup_trace_id_handler(app):
79
79
 
80
80
  content_type = response.headers.get("Content-Type", "")
81
81
 
82
- # 处理 SSE 响应 - 关键修复点
82
+ # 处理 SSE 响应
83
83
  if "text/event-stream" in content_type:
84
84
  # 流式响应不能有Content-Length,移除它
85
85
  if "Content-Length" in response.headers:
@@ -31,6 +31,7 @@ class RabbitMQListenerConfig(BaseModel):
31
31
  durable: bool = Field(True, description="是否持久化")
32
32
  auto_delete: bool = Field(False, description="是否自动删除队列")
33
33
  auto_parse_json: bool = Field(True, description="是否自动解析JSON消息")
34
+ prefetch_count: int = Field(2, description="mq同时消费数量")
34
35
 
35
36
  class Config:
36
37
  """模型配置"""