logger.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. import sys
  5. import logging
  6. import os
  7. import shutil
  8. from datetime import datetime, timedelta, date
  9. from io import TextIOBase
  10. from pathlib import Path
  11. from rich.console import Console, ConsoleOptions, ConsoleRenderable, NewLine, RenderResult
  12. from rich.highlighter import NullHighlighter
  13. from rich.logging import RichHandler
  14. from rich.rule import Rule
  15. from typing import Callable, List
  16. def cleanup_logs(log_dir: str = "./log", keep_days: int = 14):
  17. """删除 log_dir 下所有早于 keep_days 的文件夹和文件"""
  18. log_path = Path(log_dir)
  19. if not log_path.exists():
  20. return # 目录都没有,直接退出
  21. keep_days_ago_ts = (datetime.now() - timedelta(days=keep_days)).timestamp()
  22. for name in os.listdir(log_path):
  23. full_path = os.path.join(log_path, name)
  24. # 忽略软链接,仅处理文件和目录
  25. if not os.path.exists(full_path):
  26. continue
  27. if os.path.isfile(full_path):
  28. # 处理 log 根目录下超过keep_days的文件
  29. try:
  30. if os.path.getmtime(full_path) < keep_days_ago_ts:
  31. os.remove(full_path)
  32. except OSError as e:
  33. logger.error(f"delete file '{full_path}' error: {e}")
  34. elif os.path.isdir(full_path):
  35. # 检查是否为 error 目录
  36. if name != 'error':
  37. continue
  38. for error_dir_name in os.listdir(full_path):
  39. error_dir_path = os.path.join(full_path, error_dir_name)
  40. if not os.path.isdir(error_dir_path):
  41. continue
  42. # 处理 log/error 根目录下超过keep_days的文件夹
  43. try:
  44. if os.path.getmtime(error_dir_path) < keep_days_ago_ts:
  45. # 递归删除整个目录及其内容
  46. shutil.rmtree(error_dir_path)
  47. except OSError as e:
  48. logger.error(f"delete dir '{error_dir_path}' error: {e}")
  49. def empty_function(*args, **kwargs):
  50. pass
  51. # Ensure running in Alas root folder
  52. os.chdir(os.path.join(os.path.dirname(__file__), '../'))
  53. # cnocr will set root logger in cnocr.utils
  54. # Delete logging.basicConfig to avoid logging the same message twice.
  55. logging.basicConfig = empty_function
  56. logging.raiseExceptions = True # Set True if wanna see encode errors on console
  57. # Remove HTTP keywords (GET, POST etc.)
  58. # RichHandler.KEYWORDS = []
  59. # def show_handlers(handlers):
  60. # # 获取并打印日志记录器中处理器的信息
  61. # for handler in logger.handlers:
  62. # # 获取处理器的类名
  63. # handler_class = handler.__class__.__name__
  64. # print(f"Handler class: {handler_class}")
  65. #
  66. # # 获取处理器的级别
  67. # handler_level = logging.getLevelName(handler.level)
  68. # print(f"Handler level: {handler_level}")
  69. #
  70. # # 获取处理器的格式化器
  71. # formatter = handler.formatter
  72. # if formatter is not None:
  73. # formatter_class = formatter.__class__.__name__
  74. # print(f"Formatter class: {formatter_class}")
  75. #
  76. # # 其他处理器的属性和方法,根据需要进行获取和打印
  77. # print() # 打印空行,用于分隔处理器的信息
  78. # Logger init
  79. logger_debug = False
  80. logger = logging.getLogger('oas')
  81. logger.setLevel(logging.DEBUG if logger_debug else logging.INFO)
  82. file_formatter = logging.Formatter(
  83. fmt='%(asctime)s.%(msecs)03d | %(filename)20s:%(lineno)04d | %(levelname)8s | %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
  84. console_formatter = logging.Formatter(
  85. fmt='%(asctime)s.%(msecs)03d │ %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
  86. flutter_formatter = logging.Formatter(
  87. fmt='| %(asctime)s.%(msecs)03d | %(message)08s', datefmt='%H:%M:%S')
  88. # ======================================================================================================================
  89. # Set console logger
  90. # ======================================================================================================================
  91. console_hdlr = RichHandler(
  92. console=Console(
  93. width=120
  94. ),
  95. show_path=False,
  96. show_time=False,
  97. rich_tracebacks=True,
  98. tracebacks_show_locals=True,
  99. tracebacks_extra_lines=3,
  100. tracebacks_width=160
  101. )
  102. console_hdlr.setFormatter(console_formatter)
  103. # 控制台写失败时 logging 会往 stderr 打 traceback,stderr 同样失效就是二次抛错
  104. console_hdlr.handleError = empty_function
  105. logger.addHandler(console_hdlr)
  106. # ======================================================================================================================
  107. # Set file
  108. # ======================================================================================================================
  109. class RichFileHandler(RichHandler):
  110. # Rename
  111. pass
  112. # Add file logger
  113. pyw_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
  114. def set_file_logger(name=pyw_name, *, do_cleanup=False):
  115. if '_' in name:
  116. name = name.split('_', 1)[0]
  117. log_file = f'./log/{date.today()}_{name}.txt'
  118. try:
  119. file = open(log_file, mode='a', encoding='utf-8')
  120. except FileNotFoundError:
  121. os.mkdir('./log')
  122. file = open(log_file, mode='a', encoding='utf-8')
  123. file_console = Console(
  124. file=file,
  125. no_color=True,
  126. highlight=False,
  127. width=160,
  128. )
  129. hdlr = RichFileHandler(
  130. console=file_console,
  131. show_path=False,
  132. show_time=False,
  133. show_level=False,
  134. rich_tracebacks=True,
  135. tracebacks_show_locals=True,
  136. tracebacks_extra_lines=3,
  137. tracebacks_width=160,
  138. highlighter=NullHighlighter(),
  139. )
  140. hdlr.setFormatter(file_formatter)
  141. logger.handlers = [h for h in logger.handlers if not isinstance(
  142. h, (logging.FileHandler, RichFileHandler))]
  143. logger.addHandler(hdlr)
  144. logger.log_file = log_file
  145. # ---------- 可选:清理旧文件 ----------
  146. if do_cleanup:
  147. cleanup_logs()
  148. logger.info("Log cleanup finished")
  149. # ======================================================================================================================
  150. # Set flutter
  151. # ======================================================================================================================
  152. class FlutterHandler(RichHandler):
  153. # Rename
  154. pass
  155. class FlutterConsole(Console):
  156. """
  157. Force full feature console
  158. but not working lol :(
  159. """
  160. @property
  161. def options(self) -> ConsoleOptions:
  162. return ConsoleOptions(
  163. max_height=self.size.height,
  164. size=self.size,
  165. legacy_windows=False,
  166. min_width=1,
  167. max_width=self.width,
  168. encoding='utf-8',
  169. is_terminal=False,
  170. )
  171. class FlutterLogStream(TextIOBase):
  172. def __init__(self, *args, func: Callable[[ConsoleRenderable], None] = None, **kwargs):
  173. super().__init__(*args, **kwargs)
  174. self._func = func
  175. def write(self, msg: str) -> int:
  176. if isinstance(msg, bytes):
  177. msg = msg.decode("utf-8")
  178. self._func(msg)
  179. return len(msg)
  180. def set_func_logger(func):
  181. stream = FlutterLogStream(func=func)
  182. stream_console = Console(
  183. file=stream,
  184. force_terminal=False,
  185. force_interactive=False,
  186. no_color=True,
  187. highlight=False,
  188. width=80,
  189. )
  190. hdlr = FlutterHandler(
  191. console=stream_console,
  192. show_path=False,
  193. show_time=False,
  194. show_level=True,
  195. rich_tracebacks=True,
  196. tracebacks_show_locals=True,
  197. tracebacks_extra_lines=3,
  198. highlighter=NullHighlighter(),
  199. )
  200. hdlr.setFormatter(flutter_formatter)
  201. logger.addHandler(hdlr)
  202. # ======================================================================================================================
  203. # Set print format
  204. # ======================================================================================================================
  205. def _get_renderables(
  206. self: Console, *objects, sep=" ", end="\n", justify=None, emoji=None, markup=None, highlight=None,
  207. ) -> List[ConsoleRenderable]:
  208. """
  209. Refer to rich.console.Console.print()
  210. """
  211. if not objects:
  212. objects = (NewLine(),)
  213. render_hooks = self._render_hooks[:]
  214. with self:
  215. renderables = self._collect_renderables(
  216. objects,
  217. sep,
  218. end,
  219. justify=justify,
  220. emoji=emoji,
  221. markup=markup,
  222. highlight=highlight,
  223. )
  224. for hook in render_hooks:
  225. renderables = hook.process_renderables(renderables)
  226. return renderables
  227. def print(*objects: ConsoleRenderable, **kwargs):
  228. for hdlr in logger.handlers:
  229. try:
  230. if isinstance(hdlr, FlutterHandler):
  231. for renderable in _get_renderables(hdlr.console, *objects, **kwargs):
  232. hdlr.console.file._func(str(renderable))
  233. elif isinstance(hdlr, RichHandler):
  234. hdlr.console.print(*objects)
  235. except Exception as e:
  236. # 控制台写失败不能中断业务,只提示一次
  237. if not getattr(logger, 'console_error', False):
  238. logger.console_error = True
  239. logger.warning(f'Console output is unavailable: {e!r}')
  240. class GuiRule(Rule):
  241. def __rich_console__(
  242. self, console: Console, options: ConsoleOptions
  243. ) -> RenderResult:
  244. options.max_width = 80
  245. return super().__rich_console__(console, options)
  246. def __str__(self):
  247. total_width = 80
  248. cell_len = len(self.title) + 2
  249. aside_len = (total_width - cell_len) // 2
  250. left = self.characters * aside_len
  251. right = self.characters * (total_width - cell_len - aside_len)
  252. if self.title:
  253. space = ' '
  254. else:
  255. space = self.characters
  256. return f"{left}{space}{self.title}{space}{right}\n"
  257. def __repr__(self):
  258. return self.__str__()
  259. def rule(title="", *, characters="─", style="rule.line", end="\n", align="center"):
  260. rule = GuiRule(title=title, characters=characters,
  261. style=style, end=end)
  262. print(rule)
  263. def hr(title, level=3):
  264. title = str(title).upper()
  265. if level == 1:
  266. logger.rule(title, characters='═')
  267. logger.info(title)
  268. if level == 2:
  269. logger.rule(title, characters='─')
  270. logger.info(title)
  271. if level == 3:
  272. logger.info(f"[bold]<<< {title} >>>[/bold]", extra={"markup": True})
  273. if level == 0:
  274. logger.rule(characters='═')
  275. logger.rule(title, characters='─')
  276. logger.rule(characters='═')
  277. def attr(name, text):
  278. logger.info('[%s] %s' % (str(name), str(text)))
  279. def attr_align(name, text, front='', align=22):
  280. name = str(name).rjust(align)
  281. if front:
  282. name = front + name[len(front):]
  283. logger.info('%s: %s' % (name, str(text)))
  284. def show():
  285. logger.info('INFO')
  286. logger.warning('WARNING')
  287. logger.debug('DEBUG')
  288. logger.error('ERROR')
  289. logger.critical('CRITICAL')
  290. logger.hr('hr0', 0)
  291. logger.hr('hr1', 1)
  292. logger.hr('hr2', 2)
  293. logger.hr('hr3', 3)
  294. logger.info(r'Brace { [ ( ) ] }')
  295. logger.info(r'True, False, None')
  296. logger.info(r'E:/path\\to/alas/alas.exe, /root/alas/, ./relative/path/log.txt')
  297. logger.info('Tests very long strings. Tests very long strings. Tests very long strings. Tests very long strings. Tests very long strings.')
  298. local_var1 = 'This is local variable'
  299. # Line before exception
  300. raise Exception("Exception")
  301. # Line below exception
  302. def error_convert(func):
  303. def error_wrapper(msg, *args, **kwargs):
  304. if isinstance(msg, Exception):
  305. msg = f'{type(msg).__name__}: {msg}'
  306. return func(msg, *args, **kwargs)
  307. return error_wrapper
  308. logger.error = error_convert(logger.error)
  309. logger.hr = hr
  310. logger.attr = attr
  311. logger.attr_align = attr_align
  312. logger.set_file_logger = set_file_logger
  313. logger.set_func_logger = set_func_logger
  314. logger.rule = rule
  315. logger.print = print
  316. logger.log_file: str
  317. logger.set_file_logger()
  318. logger.hr('Start', level=0)