scpkg 0.1.7__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.
sc92_lib/__init__.py ADDED
@@ -0,0 +1,69 @@
1
+ """个人自用工具箱。
2
+
3
+ 单实例文件锁、轮转日志、全局异常钩子(主线程 + 子线程)、一次性 MQTT 发布、
4
+ YAML 配置读写、值转 YAML 文本、工作时段判断、局部异常兜底、钉钉机器人通知。
5
+
6
+ 公开 API 一律从包根 `sc92_lib` 导入;完整说明见 README。
7
+ """
8
+
9
+ import logging
10
+
11
+ # logging 必须排在任何子模块之前:import logging 时就已把 logging.shutdown 注册进
12
+ # atexit,而本包在 check_running_lock 里注册"退出时释放锁"更晚;atexit 是 LIFO
13
+ # (先注册后执行),所以退出顺序才是"先放锁、后关日志"(3.6 上靠它规避 Logging error)。
14
+
15
+ # 业务与库内共用的命名 logger:业务侧 from sc92_lib import logger 后直接用
16
+ # logger.info / logger.debug;handler 仍由 init_logging_config() 挂在 root 上。
17
+ logger = logging.getLogger("sc92_lib")
18
+ logger.setLevel(logging.DEBUG)
19
+
20
+ # 导入顺序与脚本头部的调用顺序保持一致:① 日志 → ② 单实例锁 → ③ 异常钩子
21
+ from .paths import (
22
+ default_lock_file,
23
+ default_log_file,
24
+ default_yaml_file,
25
+ script_dir,
26
+ script_name,
27
+ )
28
+ from .init_logger import init_logger
29
+ from .init_logging_config import init_logging_config
30
+ from .check_running_lock import check_running_lock
31
+ from .enable_exception_logging import (
32
+ enable_exception_logging,
33
+ handle_global_exception,
34
+ handle_thread_exception,
35
+ )
36
+ from .try_run import try_run
37
+ from .mqtt_publisher import MqttPublisher
38
+ from .dingtalk_robot import DingTalkRobot
39
+ from .yaml_config import read_yaml, write_yaml
40
+ from .to_yaml import to_yaml
41
+ from .is_worktime import is_worktime
42
+
43
+ __version__ = "0.1.7"
44
+ # 每次更新功能后,手动把这里改成当时的日期时间(YYYY-MM-DD HH:MM:SS)
45
+ __build_time__ = "2026-11-16 02:49:35"
46
+
47
+ __all__ = [
48
+ "__version__", # 当前包版本号
49
+ "__build_time__", # 本版构建时间:YYYY-MM-DD HH:MM:SS(更新功能后手动改)
50
+ "logger", # 命名 logger(sc92_lib),业务直接用 logger.info/debug
51
+ "init_logger", # 新业务日志初始化:命名 logger + 只收自己的日志(幂等)
52
+ "script_dir", # 入口脚本所在目录(兼容 exe 与 python -m)
53
+ "script_name", # 入口脚本名(不含扩展名,兼容 exe 与 python -m)
54
+ "init_logging_config", # 旧版日志初始化(root);仅保留给老业务,新业务用 init_logger
55
+ "default_log_file", # 推导默认日志路径前缀 <脚本目录>/logs/<脚本名>
56
+ "check_running_lock", # 单实例文件锁:抢不到锁按策略退出或返回 False
57
+ "default_lock_file", # 推导默认锁文件路径 <脚本目录>/<脚本名>.running.lock
58
+ "handle_global_exception", # sys.excepthook 实现:主线程未捕获异常写日志
59
+ "handle_thread_exception", # threading.excepthook 实现:子线程未捕获异常写日志
60
+ "enable_exception_logging", # 一键挂载主线程 + 子线程的全局异常钩子
61
+ "try_run", # 局部异常兜底:with 包住一段代码,抛异常写日志并吞掉、不中断
62
+ "MqttPublisher", # 一次性 MQTT 发布器:连接、发一条、断开
63
+ "DingTalkRobot", # 钉钉自定义机器人(加签):一条 text/markdown,只用标准库、不抛
64
+ "read_yaml", # 读 YAML 原样返回(不校验顶层类型),仅文件缺失时写模板并退出
65
+ "write_yaml", # 把 dict/list/str/int/float/bool/None 写成 YAML 文件(config 在前,路径可选)
66
+ "default_yaml_file", # 推导默认配置文件路径 <脚本目录>/configs/<脚本名>.config.yaml
67
+ "to_yaml", # 把值尽量转成 YAML 文本,失败则原样返回
68
+ "is_worktime", # 按星期几 + HHMM 时段判断当前时间是否在工作时间内
69
+ ]
@@ -0,0 +1,96 @@
1
+ """单实例运行检查:用 filelock 抢一把独占锁。
2
+
3
+ 导出 `check_running_lock()`;`default_lock_file()` 从 `paths` 复用(API 不变)。
4
+
5
+ 失败约定:撞锁时按 `on_conflict` 退出(默认 `exit(1)`)或返回 False;参数写错同样
6
+ `exit(1)`。锁文件生命周期与 3.6 退出报错的规避见 README「单实例锁」。
7
+ """
8
+
9
+ import atexit
10
+ import logging
11
+ import pathlib
12
+ import sys
13
+ from typing import Optional
14
+
15
+ from .paths import default_lock_file
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+ _held_locks: dict = {}
20
+
21
+
22
+ def _release_held_locks() -> None:
23
+ """进程退出前主动释放所有锁(兼容处理,不属于单实例逻辑)。
24
+
25
+ 针对 Python 3.6 + filelock 3.4.1 的退出报错:锁释放挂在 `FileLock.__del__` 上,
26
+ 而 `__del__` 到解释器关闭阶段才跑,那时 logging 已被拆掉,`release()` 里的 DEBUG
27
+ 日志会 `open()` 日志文件并抛 `NameError`,在 stderr 打出两段 "--- Logging error ---"。
28
+ 提前释放后 `__del__` 无事可做。
29
+
30
+ 对 3.14 / filelock 4.x 无害:进程结束本来就要放锁,只是提前到 logging 还活着时做。
31
+ """
32
+ while _held_locks:
33
+ _lock_file, lock = _held_locks.popitem()
34
+ try:
35
+ lock.release()
36
+ except Exception:
37
+ pass
38
+
39
+
40
+ # 必须早于 logging.shutdown 执行:atexit 是 LIFO,而 logging.shutdown 在 import logging
41
+ # 时就已注册(更早),所以这里会先跑。顺序反了,3.6 退出时的 "Logging error" 会重现。
42
+ atexit.register(_release_held_locks)
43
+
44
+
45
+ def check_running_lock(lock_file: Optional[str] = None, on_conflict: str = "exit") -> bool:
46
+ """尝试抢到"本脚本已在运行"这把独占锁。
47
+
48
+ 参数:
49
+ lock_file: 锁文件路径,省略时为 `<脚本目录>/<脚本名>.running.lock`。
50
+ on_conflict: 撞锁时的策略。
51
+ `"exit"`(默认):记 ERROR 后 `sys.exit(1)`;
52
+ `"return"`:记 ERROR 后返回 False,由调用方自己善后。
53
+
54
+ 返回:
55
+ 抢到锁返回 True;`on_conflict="return"` 且锁被占用时返回 False。
56
+
57
+ 退出:
58
+ `on_conflict` 不是这两个值,或 `on_conflict="exit"` 撞锁时,`exit(1)`。
59
+
60
+ 注意:
61
+ - 只在脚本开头调用一次。锁按文件判定(绝对路径、`.\\` 前缀、大小写都不影响),
62
+ 同一进程第二次抢同一个 lock_file 必然被自己上次的锁挡住,默认策略下等于自杀。
63
+ - "单实例"的范围是"这个目录下的这个脚本名":改名、复制、换目录都是另一把锁。
64
+ 需要跨目录/跨脚本名互斥,请显式传同一个绝对路径。
65
+ - 函数会顺手创建锁文件的父目录(filelock 3.4.1 不会建)。
66
+ - 锁文件是 0 字节占位文件,持锁期间别去读它(会 PermissionError)。
67
+ 锁随进程结束释放,残留文件不影响下次抢锁,别用"文件是否存在"判断有没有实例在跑。
68
+ """
69
+ from filelock import FileLock, Timeout
70
+
71
+ if on_conflict not in ("exit", "return"):
72
+ logger.error(f'on_conflict 必须是 "exit" 或 "return", 当前收到的值是 {on_conflict!r}')
73
+ sys.exit(1)
74
+
75
+ if lock_file is None:
76
+ lock_file = default_lock_file()
77
+
78
+ # 父目录自己建:filelock 4.x 的 acquire() 会 mkdir,3.4.1(3.6 上的最高版本)不会,
79
+ # 不建就会在 os.open 处 FileNotFoundError。这样两代 filelock 行为一致。
80
+ pathlib.Path(str(lock_file)).parent.mkdir(parents=True, exist_ok=True)
81
+
82
+ lock = FileLock(str(lock_file), timeout=0)
83
+ try:
84
+ # 不用 acquire(blocking=False):filelock 3.4.1 没有 blocking 参数。
85
+ # 构造时 timeout=0 + 直接 acquire() 在两代 filelock 上语义一致(抢不到即 Timeout)。
86
+ lock.acquire()
87
+ except Timeout:
88
+ logger.error(f"老程序正在运行,新程序运行退出(锁文件:{lock_file})")
89
+ if on_conflict == "exit":
90
+ sys.exit(1)
91
+ return False
92
+
93
+ # 留住引用:局部变量出作用域会释放锁,字典常驻则锁在整个进程存活期间都被持有。
94
+ _held_locks[str(lock_file)] = lock
95
+ logger.info(f"老程序未运行,新程序继续执行(锁文件:{lock_file})")
96
+ return True
@@ -0,0 +1,131 @@
1
+ """钉钉群自定义机器人(加签)发送器:`DingTalkRobot`。
2
+
3
+ 凭据只来自构造函数参数:本文件不硬编码、不读环境变量(本包会发布到 PyPI,源码里的
4
+ 任何真实凭据都会公开)。建议放在自己的 YAML 配置里,用 `read_yaml()` 读出来再传。
5
+ 只用标准库 urllib 发 POST,不引入 requests 之类的第三方依赖。
6
+
7
+ 失败约定:构造只保存参数,不校验也不抛异常;`send()` 负责校验和发送,参数错误、
8
+ 网络 / HTTP / JSON 异常都 `logger.error` + 返回 False,不抛 Exception
9
+ (SystemExit / KeyboardInterrupt 属于主动退出,照常向外抛)。
10
+ """
11
+
12
+ import base64
13
+ import hashlib
14
+ import hmac
15
+ import json
16
+ import logging
17
+ import time
18
+ import urllib.parse
19
+ import urllib.request
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ class DingTalkRobot:
25
+ """钉钉群自定义机器人(加签方式)发送器:一次 `send()` 发一条消息。
26
+
27
+ 只走加签方式,没有关键字 / IP 白名单分支。
28
+ """
29
+
30
+ def __init__(self, access_token, secret, at_mobile=None):
31
+ """保存凭据与默认 @ 名单,不做校验(校验在 send() 里)。
32
+
33
+ 参数:
34
+ access_token: 机器人 webhook 地址里的 access_token。
35
+ secret: 加签密钥(SEC 开头那串)。
36
+ at_mobile: 实例默认要 @ 的手机号列表,省略为不 @ 任何人。
37
+ """
38
+ self.access_token = access_token
39
+ self.secret = secret
40
+ self.at_mobile = at_mobile or []
41
+
42
+ def send(self, msg, msgtype="text", at_mobile=None):
43
+ """发一条 text 或 markdown 消息;只有钉钉返回 errcode==0 才返回 True。
44
+
45
+ 参数:
46
+ msg: text 时直接 `str(msg)` 当正文(dict 也照发,方便把 JSON 当文本发);
47
+ markdown 时必须是字典,否则记 ERROR 并返回 False、不发送。
48
+ msgtype: `"text"`(默认)或 `"markdown"`,其它值记 ERROR 并返回 False、
49
+ 不发送。
50
+ at_mobile: 单次覆盖实例默认的 @ 名单;不传(None)用 `self.at_mobile`。
51
+ 最终必须是 list / tuple 且元素都是字符串,空列表表示不 @ 任何人。
52
+
53
+ 返回:
54
+ 钉钉响应 `errcode == 0` 时返回 True;参数错误、连接失败、超时、HTTP 非 2xx、
55
+ 响应不是 JSON / 不是字典、errcode != 0 都返回 False。
56
+
57
+ 退出:
58
+ 不退出(SystemExit / KeyboardInterrupt 除外)。
59
+
60
+ 注意:
61
+ - access_token / secret 必须是非空字符串。
62
+ - 要发 markdown 必须显式传 `msgtype="markdown"`,否则会按 text 走 `str()`。
63
+ - 整条消息内容会写进 INFO 日志,别用它发明文密码 / token;
64
+ 完整签名 URL(含 access_token)不落日志,只落 errcode 之类结果。
65
+ """
66
+ try:
67
+ logger.info(f"通过钉钉机器人发送消息,消息类型 {msgtype},消息内容:\n{msg}")
68
+
69
+ if not isinstance(self.access_token, str) or not self.access_token.strip():
70
+ logger.error("钉钉参数错误:access_token 必须是非空字符串,消息未发送")
71
+ return False
72
+ if not isinstance(self.secret, str) or not self.secret.strip():
73
+ logger.error("钉钉参数错误:secret 必须是非空字符串,消息未发送")
74
+ return False
75
+
76
+ if msgtype not in ("text", "markdown"):
77
+ logger.error("msgtype 赋值错误,只支持 text、markdown,消息未发送")
78
+ return False
79
+ if msgtype == "markdown" and not isinstance(msg, dict):
80
+ logger.error(f"钉钉 markdown 消息的 msg 必须是字典,收到 {type(msg).__name__},消息未发送")
81
+ return False
82
+
83
+ at_list = at_mobile if at_mobile is not None else self.at_mobile
84
+ if not isinstance(at_list, (list, tuple)):
85
+ logger.error(
86
+ f"钉钉参数错误:at_mobile 必须是 list 或 tuple,"
87
+ f"收到 {type(at_list).__name__},消息未发送"
88
+ )
89
+ return False
90
+ for i, mobile in enumerate(at_list):
91
+ if not isinstance(mobile, str):
92
+ logger.error(
93
+ f"钉钉参数错误:at_mobile[{i}] 必须是字符串,"
94
+ f"收到 {type(mobile).__name__},消息未发送"
95
+ )
96
+ return False
97
+
98
+ # 加签:待签串 = timestamp + "\n" + secret,key = secret;
99
+ # HMAC-SHA256 → base64 → urlencode,拼进 webhook URL。
100
+ ts = str(round(time.time() * 1000))
101
+ h = hmac.new(self.secret.encode(), f"{ts}\n{self.secret}".encode(), hashlib.sha256).digest()
102
+ sign = urllib.parse.quote_plus(base64.b64encode(h).decode())
103
+ url = (f"https://oapi.dingtalk.com/robot/send?access_token={self.access_token}"
104
+ f"&timestamp={ts}&sign={sign}")
105
+
106
+ at = {"isAtAll": False, "atMobiles": list(at_list)}
107
+ if msgtype == "text":
108
+ body = {"msgtype": "text", "text": {"content": str(msg)}, "at": at}
109
+ else: # markdown
110
+ body = {"msgtype": "markdown", "markdown": msg, "at": at}
111
+
112
+ # urllib 版等价于 requests.post(url, data=json, headers=..., timeout=10).json()
113
+ req = urllib.request.Request(
114
+ url,
115
+ data=json.dumps(body).encode("utf-8"),
116
+ headers={"Content-Type": "application/json"},
117
+ method="POST",
118
+ )
119
+ with urllib.request.urlopen(req, timeout=10) as resp:
120
+ res = json.loads(resp.read().decode("utf-8", errors="replace"))
121
+ if not isinstance(res, dict):
122
+ logger.error(f"钉钉响应格式异常:期望字典,收到 {type(res).__name__}:{res}")
123
+ return False
124
+ if res.get("errcode") == 0:
125
+ logger.info("钉钉消息发送成功")
126
+ return True
127
+ logger.error(f"钉钉消息发送失败:{res}")
128
+ return False
129
+ except Exception as e:
130
+ logger.error(f"钉钉机器人发送异常:{type(e).__name__}: {e}")
131
+ return False
@@ -0,0 +1,99 @@
1
+ """全局未捕获异常日志:主线程(sys.excepthook)+ 子线程。
2
+
3
+ 子线程不受 `sys.excepthook` 管辖,不额外挂钩子的话,traceback 只到 stderr、进不了
4
+ 日志文件。Python 3.8+ 用原生 `threading.excepthook`;3.6/3.7 走包装
5
+ `Thread._bootstrap_inner` 的兼容实现。
6
+
7
+ 失败约定:只记录日志,不改变解释器的退出行为(退出码仍由解释器决定)。
8
+ """
9
+
10
+ import logging
11
+ import sys
12
+ import threading
13
+ import traceback
14
+ from types import SimpleNamespace
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ _thread_hook_installed = False
19
+
20
+
21
+ def handle_global_exception(exc_type, exc_value, exc_traceback) -> None:
22
+ """`sys.excepthook` 的实现:把主线程的未捕获异常写进日志。"""
23
+ tb_str = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
24
+ logger.error(f"全局异常捕获:\n{tb_str}")
25
+
26
+
27
+ def handle_thread_exception(args) -> None:
28
+ """`threading.excepthook` 的实现:把子线程的未捕获异常写进日志。"""
29
+ tb_str = "".join(traceback.format_exception(
30
+ args.exc_type, args.exc_value, args.exc_traceback))
31
+ thread_name = getattr(args.thread, "name", "<unknown>")
32
+ logger.error(f"子线程未捕获异常(线程:{thread_name}):\n{tb_str}")
33
+
34
+
35
+ def enable_exception_logging() -> None:
36
+ """挂上主线程 + 子线程的未捕获异常钩子。
37
+
38
+ 等价于 `sys.excepthook = handle_global_exception` 加上
39
+ `threading.excepthook = handle_thread_exception`(3.6/3.7 为兼容实现)。
40
+
41
+ 退出:
42
+ 不退出。应在 `init_logging_config()` 之后调用:本函数收尾那条 INFO 走命名
43
+ logger,初始化前调用不会写进文件(root 还没有 handler),但也不会触发
44
+ `basicConfig()`;后面的 `init_logging_config(force=True)` 仍可正常接管。
45
+ """
46
+ sys.excepthook = handle_global_exception
47
+ _install_thread_exception_hook()
48
+
49
+ # 钩子挂上就留痕:看到这行说明主线程和子线程的未捕获异常都会写进日志
50
+ logger.info("sc92_lib 全局异常捕获已开启(主线程 + 子线程)")
51
+
52
+
53
+ def _install_thread_exception_hook() -> None:
54
+ """把 handle_thread_exception 挂到子线程上。
55
+
56
+ 3.8+ 有原生 `threading.excepthook`,直接赋值即可。
57
+ 3.6/3.7 没有这个钩子(给模块赋属性不会报错,但 CPython 内部不读它,等于没挂),
58
+ 改为包装 `Thread._bootstrap_inner`:在其中临时把 `self.run` 换成带日志的版本,
59
+ 这样连"继承 Thread 并重写 run()"的写法也能覆盖(只包 run 会漏掉这类子类)。
60
+ 异常记完日志后照常向上抛,3.6/3.7 原本往 stderr 打印 traceback 的行为保持不变。
61
+ """
62
+ global _thread_hook_installed
63
+ if hasattr(threading, "excepthook"):
64
+ threading.excepthook = handle_thread_exception
65
+ _thread_hook_installed = True
66
+ return
67
+ if _thread_hook_installed:
68
+ return
69
+
70
+ original_bootstrap_inner = threading.Thread._bootstrap_inner
71
+
72
+ def _bootstrap_inner(self):
73
+ original_run = self.run
74
+
75
+ def _run():
76
+ try:
77
+ original_run()
78
+ except SystemExit:
79
+ raise # 交回原实现:3.6/3.7 里子线程的 SystemExit 依旧被静默吞掉
80
+ except Exception:
81
+ handle_thread_exception(SimpleNamespace(
82
+ exc_type=sys.exc_info()[0],
83
+ exc_value=sys.exc_info()[1],
84
+ exc_traceback=sys.exc_info()[2],
85
+ thread=self,
86
+ ))
87
+ raise # 记完再抛,保留 3.6/3.7 原本往 stderr 打印 traceback 的行为
88
+
89
+ self.run = _run
90
+ try:
91
+ original_bootstrap_inner(self)
92
+ finally:
93
+ try:
94
+ del self.run
95
+ except AttributeError:
96
+ pass
97
+
98
+ threading.Thread._bootstrap_inner = _bootstrap_inner
99
+ _thread_hook_installed = True
@@ -0,0 +1,147 @@
1
+ """新业务日志初始化:配置命名 logger `sc92_lib`,只收自己的日志。
2
+
3
+ 用法::
4
+
5
+ from sc92_lib import init_logger, logger
6
+
7
+ init_logger() # 只需要在入口脚本调用一次;重复调用是幂等的
8
+ logger.info("业务日志")
9
+ logger.debug("业务调试")
10
+
11
+ 与旧的 `init_logging_config()` 的区别:
12
+
13
+ - `init_logger()` 把 handler 挂在 `sc92_lib` 上,并设置 `propagate=False`;
14
+ - root 不动,第三方 logger(filelock / paho / urllib3 等)不会写进本文件;
15
+ - 业务必须使用 `logger.*`;漏改的 `logging.*` 不会落盘(WARNING 及以上只到
16
+ stderr 的 lastResort)。
17
+
18
+ 幂等约定:
19
+
20
+ - 第一次调用生效;
21
+ - 后续调用(未传 force)不会重复添加 handler,只会重新确保 `sc92_lib` 的级别为
22
+ DEBUG、`propagate=False`;
23
+ - `force=True` 会移除并关闭 `sc92_lib` 上现有的 handler,然后重建;
24
+ - 多个模块都调用 `init_logger()` 时,以第一次调用的参数为准。
25
+ """
26
+
27
+ import logging
28
+ import logging.handlers
29
+ import pathlib
30
+ import sys
31
+ import threading
32
+ from typing import List, Optional, Tuple
33
+
34
+ from .paths import default_log_file
35
+
36
+ _FORMAT = "%(asctime)s [%(levelname)-8s] %(filename)12s:%(lineno)-4d %(funcName)-12s: %(message)s"
37
+
38
+ # 标记本函数创建的 handler,重复调用时只认这些,不会把用户自己加的 handler 误判为已初始化。
39
+ _MANAGED_ATTR = "_sc92_lib_managed"
40
+
41
+ _lock = threading.RLock()
42
+
43
+
44
+ def _build_handlers(
45
+ log_file: str,
46
+ max_bytes: int,
47
+ backup_count: int,
48
+ ) -> Tuple[List[logging.Handler], pathlib.Path, pathlib.Path]:
49
+ """创建 debug / info / 控制台三个 handler;失败时关掉已创建的再抛出。"""
50
+ debug_path = pathlib.Path(f"{log_file}_debug.log")
51
+ info_path = pathlib.Path(f"{log_file}_info.log")
52
+ debug_path.parent.mkdir(parents=True, exist_ok=True)
53
+
54
+ formatter = logging.Formatter(_FORMAT)
55
+ created: List[logging.Handler] = []
56
+ try:
57
+ debug_handler = logging.handlers.RotatingFileHandler(
58
+ debug_path, maxBytes=max_bytes, backupCount=backup_count, encoding="utf-8"
59
+ )
60
+ debug_handler.setLevel(logging.DEBUG)
61
+ created.append(debug_handler)
62
+
63
+ info_handler = logging.handlers.RotatingFileHandler(
64
+ info_path, maxBytes=max_bytes, backupCount=backup_count, encoding="utf-8"
65
+ )
66
+ info_handler.setLevel(logging.INFO)
67
+ created.append(info_handler)
68
+
69
+ if sys.stderr is not None:
70
+ console_handler = logging.StreamHandler(sys.stderr)
71
+ console_handler.setLevel(logging.INFO)
72
+ created.append(console_handler)
73
+ except Exception:
74
+ for handler in created:
75
+ try:
76
+ handler.close()
77
+ except Exception:
78
+ pass
79
+ raise
80
+
81
+ for handler in created:
82
+ handler.setFormatter(formatter)
83
+ setattr(handler, _MANAGED_ATTR, True)
84
+ return created, debug_path, info_path
85
+
86
+
87
+ def init_logger(
88
+ log_file: Optional[str] = None,
89
+ max_bytes: int = 10 * 1024 * 1024,
90
+ backup_count: int = 7,
91
+ force: bool = False,
92
+ ) -> None:
93
+ """配置命名 logger `sc92_lib`:两个轮转文件 + 控制台,只收自己人写的日志。
94
+
95
+ 参数:
96
+ log_file: 日志路径前缀,省略时为 `<脚本目录>/logs/<脚本名>`。
97
+ max_bytes: 单个日志文件的大小上限,默认 10 MB。
98
+ backup_count: 轮转保留的备份份数,默认 7。
99
+ force: 是否移除并关闭 `sc92_lib` 上已有的 handler 后重建,默认 False。
100
+
101
+ 退出:
102
+ 不退出;目录创建或日志文件打开失败时,异常照常抛出。
103
+
104
+ 注意:
105
+ - handler 只挂在 `sc92_lib` 上,`logger.propagate=False`,root 保持原样;
106
+ - 业务必须用 `logger.info/debug/error` 写日志;`logging.*` 不会进本文件;
107
+ - 第三方库的 WARNING 及以上只会走 stderr 的 `lastResort`,不会落盘;
108
+ - 幂等:重复调用不会重复添加 handler;多模块调用时第一次的参数生效;
109
+ - 与 `init_logging_config()` 不要在同一进程里混用(旧业务已结束,新业务只用本函数)。
110
+ """
111
+ target = logging.getLogger("sc92_lib")
112
+
113
+ with _lock:
114
+ managed = [h for h in target.handlers if getattr(h, _MANAGED_ATTR, False)]
115
+ if managed and not force:
116
+ # 已初始化:不重复加 handler,只确保级别与传播设置没被改掉。
117
+ target.setLevel(logging.DEBUG)
118
+ target.propagate = False
119
+ return
120
+
121
+ if force:
122
+ for handler in list(target.handlers):
123
+ target.removeHandler(handler)
124
+ try:
125
+ handler.close()
126
+ except Exception:
127
+ pass
128
+
129
+ if log_file is None:
130
+ log_file = default_log_file()
131
+ else:
132
+ log_file = str(log_file)
133
+
134
+ handlers, debug_path, info_path = _build_handlers(
135
+ log_file, max_bytes, backup_count
136
+ )
137
+ for handler in handlers:
138
+ target.addHandler(handler)
139
+
140
+ target.setLevel(logging.DEBUG)
141
+ target.propagate = False
142
+
143
+ # __version__ 在包 __init__.py 里,延迟导入避免循环导入。
144
+ from . import __version__
145
+
146
+ target.info(f"新程序开始启动,sc92_lib 已加载,包版本: {__version__}")
147
+ target.info(f"新程序开始启动,日志初始化完成:{debug_path} / {info_path}")
@@ -0,0 +1,100 @@
1
+ """旧版日志初始化:两个轮转文件(debug / info)+ 控制台,配置 root logger。
2
+
3
+ 已弃用:新业务请用 `init_logger()`(见 `init_logger.py`)。本模块保留给老业务,
4
+ 行为不变;不再新增功能。
5
+
6
+ 导出 `init_logging_config()`;`default_log_file()` 从 `paths` 复用(API 不变)。
7
+ 建议在脚本第一行就调用,原因和"先调别的函数"的后果见 README「日志」。
8
+
9
+ 失败约定:本函数不 exit。根日志器已有 handler 且未传 force 时只往 stderr 提示,
10
+ 不做任何接管;目录创建或日志文件打开失败时,异常照常抛出。
11
+ """
12
+
13
+ import logging
14
+ import logging.handlers
15
+ import pathlib
16
+ import sys
17
+ from typing import Optional
18
+
19
+ from .paths import default_log_file
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ _FORMAT = "%(asctime)s [%(levelname)-8s] %(filename)12s:%(lineno)-4d %(funcName)-12s: %(message)s"
24
+
25
+
26
+ def init_logging_config(
27
+ log_file: Optional[str] = None,
28
+ max_bytes: int = 10 * 1024 * 1024,
29
+ backup_count: int = 7,
30
+ force: bool = False,
31
+ ) -> None:
32
+ """配置根日志器:`<前缀>_debug.log` + `<前缀>_info.log`(轮转)+ 控制台。
33
+
34
+ 已弃用:新业务请用 `init_logger()`。本函数保留给老业务,行为不变。
35
+
36
+ 参数:
37
+ log_file: 日志路径前缀,省略时为 `<脚本目录>/logs/<脚本名>`。
38
+ max_bytes: 单个日志文件的大小上限,默认 10 MB。
39
+ backup_count: 轮转保留的备份份数,默认 7。
40
+ force: 根日志器已有 handler 时是否强行接管,默认 False(只提示、不接管)。
41
+
42
+ 退出:
43
+ 不退出;目录创建或日志文件打开失败时,异常照常抛出(交给调用方 / 默认钩子)。
44
+
45
+ 注意:
46
+ - 根日志器已有 handler(pytest、Jupyter、别的库配置过,或业务自己先调了
47
+ `logging.*` 触发过 `logging.basicConfig()`)时默认什么都不做,只往 stderr
48
+ 提示一句;确实要接管就传 `force=True`,它会先移除已有 handler。
49
+ - 无论是否接管 root,都会把命名 logger `sc92_lib` 的级别设为 DEBUG,保证
50
+ `from sc92_lib import logger` 的 `logger.debug()` 可用。
51
+ - `sys.stderr` 为 None(`pythonw.exe`、PyInstaller `--noconsole`)时跳过控制台
52
+ handler,只留文件日志。
53
+ - 配置成功后先记包版本、再记两个日志文件路径,两条都带"新程序开始启动"前缀,
54
+ 用于在定时任务反复拉起时区分"新进程"和"常驻实例"(详见 README「日志」)。
55
+ """
56
+ logging.getLogger("sc92_lib").setLevel(logging.DEBUG)
57
+
58
+ if logging.root.handlers and not force:
59
+ if sys.stderr is not None:
60
+ print(
61
+ "[sc92_lib] 根日志器已有 handler,init_logging_config() 没有生效,"
62
+ "日志不会写到文件;确认要接管请传 force=True。",
63
+ file=sys.stderr,
64
+ )
65
+ return
66
+
67
+ for handler in logging.root.handlers[:]:
68
+ logging.root.removeHandler(handler)
69
+
70
+ if log_file is None:
71
+ log_file = default_log_file()
72
+
73
+ debug_path = pathlib.Path(f"{log_file}_debug.log")
74
+ info_path = pathlib.Path(f"{log_file}_info.log")
75
+ debug_path.parent.mkdir(parents=True, exist_ok=True)
76
+
77
+ debug_handler = logging.handlers.RotatingFileHandler(
78
+ debug_path, maxBytes=max_bytes, backupCount=backup_count, encoding="utf-8"
79
+ )
80
+ debug_handler.setLevel(logging.DEBUG)
81
+
82
+ info_handler = logging.handlers.RotatingFileHandler(
83
+ info_path, maxBytes=max_bytes, backupCount=backup_count, encoding="utf-8"
84
+ )
85
+ info_handler.setLevel(logging.INFO)
86
+
87
+ handlers = [debug_handler, info_handler]
88
+ if sys.stderr is not None:
89
+ console_handler = logging.StreamHandler(sys.stderr)
90
+ console_handler.setLevel(logging.INFO)
91
+ handlers.append(console_handler)
92
+
93
+ logging.basicConfig(level=logging.DEBUG, format=_FORMAT, handlers=handlers)
94
+
95
+ # 先记包版本(日志里最早的一条 INFO)。__version__ 在包 __init__.py 里,
96
+ # 这里延迟导入,避免 __init__ 与本模块循环导入。
97
+ from . import __version__
98
+
99
+ logger.info(f"新程序开始启动,sc92_lib 已加载,包版本: {__version__}")
100
+ logger.info(f"新程序开始启动,日志初始化完成:{debug_path} / {info_path}")