ygo 1.0.2__py3-none-any.whl → 1.2.12__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.
ylog/core.py DELETED
@@ -1,226 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- ---------------------------------------------
4
- Created on 2025/5/14 16:04
5
- @author: ZhangYundi
6
- @email: yundi.xxii@outlook.com
7
- ---------------------------------------------
8
- """
9
-
10
- import sys
11
- from pathlib import Path
12
- from threading import Lock
13
- from typing import Optional
14
-
15
- from loguru import logger
16
-
17
-
18
- class _Logger:
19
- """
20
- 企业级日志类,基于Loguru封装
21
-
22
- 特性:
23
- 1. 高性能:异步写入日志,避免阻塞主线程
24
- 2. 易于管理:多级别日志分离存储,按日期和大小轮转
25
- 3. 分级明确:支持 TRACE/DEBUG/INFO/WARNING/ERROR/CRITICAL 级别
26
- 4. 结构化日志:支持 JSON 格式日志输出
27
- 5. 全局异常捕获:自动记录未处理异常
28
- """
29
-
30
- _instance = None
31
- _lock = Lock()
32
-
33
- def __new__(cls, *args, **kwargs):
34
- """单例模式确保全局只有一个logger实例"""
35
- if not cls._instance:
36
- with cls._lock:
37
- if not cls._instance:
38
- cls._instance = super().__new__(cls)
39
- return cls._instance
40
-
41
- def __init__(
42
- self,
43
- log_dir: str = "logs",
44
- app_name: str = "application",
45
- retention_days: int = 7,
46
- error_retention_days: int = 30,
47
- enable_console: bool = True,
48
- enable_file: bool = True,
49
- debug_mode: bool = False
50
- ):
51
- """初始化日志系统"""
52
- # 避免重复初始化
53
- if hasattr(self, "_initialized"):
54
- return
55
- self._initialized = True
56
-
57
- # 初始化参数
58
- self.log_dir = Path(log_dir)
59
- self.app_name = app_name
60
- self.debug_mode = debug_mode
61
- self._error_retention_days = error_retention_days
62
- self._retention_days = retention_days
63
-
64
- # 创建日志目录
65
- self.log_dir.mkdir(parents=True, exist_ok=True)
66
-
67
- # 移除默认sink
68
- logger.remove()
69
-
70
- # 配置控制台日志
71
- if enable_console:
72
- self._setup_console_logging()
73
-
74
- # 配置文件日志
75
- if enable_file:
76
- self._setup_file_logging(retention_days, error_retention_days)
77
-
78
- # 全局异常捕获
79
- self._setup_global_exception_handling()
80
-
81
- def _setup_console_logging(self):
82
- """配置控制台日志"""
83
- console_format = (
84
- "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
85
- "<level>{level: <8}</level> | "
86
- "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - "
87
- "<level>{message}</level>"
88
- )
89
-
90
- logger.add(
91
- sys.stderr,
92
- level="DEBUG" if self.debug_mode else "INFO",
93
- format=console_format,
94
- colorize=True,
95
- backtrace=self.debug_mode,
96
- diagnose=self.debug_mode,
97
- enqueue=True # 异步写入
98
- )
99
-
100
- def _setup_file_logging(self, retention_days: int, error_retention_days: int):
101
- """配置文件日志"""
102
- # 通用日志格式
103
- common_format = (
104
- "{time:YYYY-MM-DD HH:mm:ss.SSS} | "
105
- "{level: <8} | "
106
- "{name}:{function}:{line} - {message}"
107
- )
108
-
109
- # 日志级别配置
110
- levels = {
111
- "TRACE": {"level": "TRACE", "retention": f"{retention_days} days", "rotation": "daily"},
112
- "DEBUG": {"level": "DEBUG", "retention": f"{retention_days} days", "rotation": "daily"},
113
- "INFO": {"level": "INFO", "retention": f"{retention_days} days", "rotation": "daily"},
114
- "WARNING": {"level": "WARNING", "retention": f"{retention_days} days", "rotation": "daily"},
115
- "ERROR": {"level": "ERROR", "retention": f"{error_retention_days} days", "rotation": "daily"},
116
- "CRITICAL": {"level": "CRITICAL", "retention": f"{error_retention_days} days", "rotation": "daily"}
117
- }
118
-
119
- for level, config in levels.items():
120
- log_file = self.log_dir / f"{self.app_name}_{level.lower()}_{{time:YYYY-MM-DD}}.log"
121
-
122
- logger.add(
123
- str(log_file),
124
- level=config["level"],
125
- format=common_format,
126
- rotation=config["rotation"],
127
- retention=config["retention"],
128
- compression="zip",
129
- backtrace=True,
130
- diagnose=self.debug_mode,
131
- enqueue=True, # 异步写入
132
- filter=lambda record, lvl=level: record["level"].name == lvl,
133
- catch=True # 捕获格式化异常
134
- )
135
-
136
- def _setup_global_exception_handling(self):
137
- """配置全局异常捕获"""
138
-
139
- def handle_exception(exc_type, exc_value, exc_traceback):
140
- """全局异常处理函数"""
141
- logger.opt(exception=(exc_type, exc_value, exc_traceback)).critical(
142
- "Unhandled exception occurred"
143
- )
144
-
145
- sys.excepthook = handle_exception
146
-
147
- def trace(self, message: str, **kwargs) -> None:
148
- """TRACE级别日志"""
149
- logger.opt(depth=1).trace(message, **kwargs)
150
-
151
- def debug(self, message: str, **kwargs) -> None:
152
- """DEBUG级别日志"""
153
- logger.opt(depth=1).debug(message, **kwargs)
154
-
155
- def info(self, message: str, **kwargs) -> None:
156
- """INFO级别日志"""
157
- logger.opt(depth=1).info(message, **kwargs)
158
-
159
- def warning(self, message: str, **kwargs) -> None:
160
- """WARNING级别日志"""
161
- logger.opt(depth=1).warning(message, **kwargs)
162
-
163
- def error(self, message: str, exc_info: Optional[BaseException] = None, **kwargs) -> None:
164
- """ERROR级别日志"""
165
- if exc_info:
166
- logger.opt(depth=1, exception=exc_info).error(message, **kwargs)
167
- else:
168
- logger.opt(depth=1).error(message, **kwargs)
169
-
170
- def critical(self, message: str, exc_info: Optional[BaseException] = None, **kwargs) -> None:
171
- """CRITICAL级别日志"""
172
- if exc_info:
173
- logger.opt(depth=1, exception=exc_info).critical(message, **kwargs)
174
- else:
175
- logger.opt(depth=1).critical(message, **kwargs)
176
-
177
- def update_config(
178
- self,
179
- log_dir: str = None,
180
- app_name: str = None,
181
- retention_days: int = None,
182
- error_retention_days: int = None,
183
- enable_console: bool = None,
184
- enable_file: bool = None,
185
- debug_mode: bool = None
186
- ):
187
- """
188
- 动态更新日志配置并重新加载日志系统
189
- 注意:这会清除已有的sink并重新创建日志文件
190
- """
191
-
192
- # 更新配置
193
- if log_dir is not None:
194
- self.log_dir = Path(log_dir)
195
- if app_name is not None:
196
- self.app_name = app_name
197
- if retention_days is not None:
198
- self._retention_days = retention_days
199
- if error_retention_days is not None:
200
- self._error_retention_days = error_retention_days
201
- if debug_mode is not None:
202
- self.debug_mode = debug_mode
203
-
204
- # 重建日志目录
205
- self.log_dir.mkdir(parents=True, exist_ok=True)
206
-
207
- # 清除现有sink
208
- logger.remove()
209
-
210
- # 重新配置控制台和文件日志
211
- if enable_console is not False:
212
- self._setup_console_logging()
213
- if enable_file is not False:
214
- self._setup_file_logging(self._retention_days, self._error_retention_days)
215
-
216
- # 初始化默认实例
217
- _default_logger = _Logger(app_name="app")
218
-
219
- # 将日志方法绑定到模块级别
220
- trace = _default_logger.trace
221
- debug = _default_logger.debug
222
- info = _default_logger.info
223
- warning = _default_logger.warning
224
- error = _default_logger.error
225
- critical = _default_logger.critical
226
- update_config = _default_logger.update_config