log.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. """Main logging part"""
  2. # Friendly Telegram (telegram userbot)
  3. # Copyright (C) 2018-2021 The Authors
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU Affero General Public License for more details.
  12. # You should have received a copy of the GNU Affero General Public License
  13. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. # █ █ ▀ █▄▀ ▄▀█ █▀█ ▀
  15. # █▀█ █ █ █ █▀█ █▀▄ █
  16. # © Copyright 2022
  17. # https://t.me/hikariatama
  18. #
  19. # 🔒 Licensed under the GNU AGPLv3
  20. # 🌐 https://www.gnu.org/licenses/agpl-3.0.html
  21. import asyncio
  22. import contextlib
  23. import inspect
  24. import json
  25. import logging
  26. import io
  27. import os
  28. import re
  29. import telethon
  30. import traceback
  31. from typing import List, Optional
  32. from logging.handlers import RotatingFileHandler
  33. from . import utils
  34. from .types import Module, BotInlineCall
  35. class HikkaException:
  36. def __init__(self, message: str, local_vars: str, full_stack: str):
  37. self.message = message
  38. self.local_vars = local_vars
  39. self.full_stack = full_stack
  40. @classmethod
  41. def from_exc_info(
  42. cls,
  43. exc_type: object,
  44. exc_value: Exception,
  45. tb: traceback.TracebackException,
  46. stack: Optional[List[inspect.FrameInfo]] = None,
  47. ) -> "HikkaException":
  48. def to_hashable(dictionary: dict) -> dict:
  49. dictionary = dictionary.copy()
  50. for key, value in dictionary.items():
  51. if isinstance(value, dict):
  52. if (
  53. getattr(getattr(value, "__class__", None), "__name__", None)
  54. == "Database"
  55. ):
  56. dictionary[key] = "<Database>"
  57. if isinstance(value, telethon.TelegramClient):
  58. dictionary[key] = "<TelegramClient>"
  59. dictionary[key] = to_hashable(value)
  60. else:
  61. try:
  62. json.dumps([value])
  63. except Exception:
  64. dictionary[key] = str(value)
  65. return dictionary
  66. full_stack = traceback.format_exc().replace(
  67. "Traceback (most recent call last):\n", ""
  68. )
  69. line_regex = r' File "(.*?)", line ([0-9]+), in (.+)'
  70. def format_line(line: str) -> str:
  71. filename_, lineno_, name_ = re.search(line_regex, line).groups()
  72. with contextlib.suppress(Exception):
  73. filename_ = os.path.basename(filename_)
  74. return (
  75. f"👉 <code>{utils.escape_html(filename_)}:{lineno_}</code> <b>in</b>"
  76. f" <code>{utils.escape_html(name_)}</code>"
  77. )
  78. filename, lineno, name = next(
  79. (
  80. re.search(line_regex, line).groups()
  81. for line in reversed(full_stack.splitlines())
  82. if re.search(line_regex, line)
  83. ),
  84. (None, None, None),
  85. )
  86. line = next(
  87. (
  88. line
  89. for line in reversed(full_stack.splitlines())
  90. if line.startswith(" ")
  91. ),
  92. "",
  93. )
  94. full_stack = "\n".join(
  95. [
  96. format_line(line)
  97. if re.search(line_regex, line)
  98. else f"<code>{utils.escape_html(line)}</code>"
  99. for line in full_stack.splitlines()
  100. ]
  101. )
  102. with contextlib.suppress(Exception):
  103. filename = os.path.basename(filename)
  104. caller = utils.find_caller(stack or inspect.stack())
  105. cause_mod = (
  106. "🪬 <b>Possible cause: method"
  107. f" </b><code>{utils.escape_html(caller.__name__)}</code><b> of module"
  108. f" </b><code>{utils.escape_html(caller.__self__.__class__.__name__)}</code>\n"
  109. if caller and hasattr(caller, "__self__") and hasattr(caller, "__name__")
  110. else ""
  111. )
  112. return HikkaException(
  113. message=(
  114. f"<b>🚫 Error!</b>\n{cause_mod}\n<b>🗄 Where:</b>"
  115. f" <code>{utils.escape_html(filename)}:{lineno}</code><b>"
  116. f" in </b><code>{utils.escape_html(name)}</code>\n😵"
  117. f" <code>{utils.escape_html(line)}</code>"
  118. " 👈\n<b>❓ What:</b>"
  119. f" <code>{utils.escape_html(''.join(traceback.format_exception_only(exc_type, exc_value)).strip())}</code>"
  120. ),
  121. local_vars=(
  122. f"<code>{utils.escape_html(json.dumps(to_hashable(tb.tb_frame.f_locals), indent=4))}</code>"
  123. ),
  124. full_stack=full_stack,
  125. )
  126. class TelegramLogsHandler(logging.Handler):
  127. """
  128. Keeps 2 buffers.
  129. One for dispatched messages.
  130. One for unused messages.
  131. When the length of the 2 together is 100
  132. truncate to make them 100 together,
  133. first trimming handled then unused.
  134. """
  135. def __init__(self, targets: list, capacity: int):
  136. super().__init__(0)
  137. self.targets = targets
  138. self.capacity = capacity
  139. self.buffer = []
  140. self.handledbuffer = []
  141. self.lvl = logging.NOTSET # Default loglevel
  142. self._queue = []
  143. self.tg_buff = []
  144. self._mods = {}
  145. self.force_send_all = False
  146. def install_tg_log(self, mod: Module):
  147. if getattr(self, "_task", False):
  148. self._task.cancel()
  149. self._mods[mod.tg_id] = mod
  150. self._task = asyncio.ensure_future(self.queue_poller())
  151. async def queue_poller(self):
  152. while True:
  153. await self.sender()
  154. await asyncio.sleep(3)
  155. def setLevel(self, level: int):
  156. self.lvl = level
  157. def dump(self):
  158. """Return a list of logging entries"""
  159. return self.handledbuffer + self.buffer
  160. def dumps(self, lvl: Optional[int] = 0, client_id: Optional[int] = None) -> list:
  161. """Return all entries of minimum level as list of strings"""
  162. return [
  163. self.targets[0].format(record)
  164. for record in (self.buffer + self.handledbuffer)
  165. if record.levelno >= lvl
  166. and (not record.hikka_caller or client_id == record.hikka_caller)
  167. ]
  168. async def _show_full_stack(
  169. self,
  170. call: BotInlineCall,
  171. bot: "aiogram.Bot", # type: ignore
  172. item: HikkaException,
  173. ):
  174. chunks = (
  175. item.message
  176. + "\n\n<b>🦝 Locals:</b>\n"
  177. + item.local_vars
  178. + "\n\n"
  179. + "<b>🪐 Full stack:</b>\n"
  180. + item.full_stack
  181. )
  182. chunks = list(utils.smart_split(*telethon.extensions.html.parse(chunks), 4096))
  183. await call.edit(chunks[0])
  184. for chunk in chunks[1:]:
  185. await bot.send_message(chat_id=call.chat_id, text=chunk)
  186. async def sender(self):
  187. self._queue = {
  188. client_id: utils.chunks(
  189. utils.escape_html(
  190. "".join(
  191. [
  192. item[0]
  193. for item in self.tg_buff
  194. if isinstance(item[0], str)
  195. and (
  196. not item[1]
  197. or item[1] == client_id
  198. or self.force_send_all
  199. )
  200. ]
  201. )
  202. ),
  203. 4096,
  204. )
  205. for client_id in self._mods
  206. }
  207. self._exc_queue = {
  208. client_id: [
  209. self._mods[client_id].inline.bot.send_message(
  210. self._mods[client_id]._logchat,
  211. item[0].message,
  212. reply_markup=self._mods[client_id].inline.generate_markup(
  213. {
  214. "text": "🪐 Full stack",
  215. "callback": self._show_full_stack,
  216. "args": (
  217. self._mods[client_id].inline.bot,
  218. item[0],
  219. ),
  220. }
  221. ),
  222. )
  223. for item in self.tg_buff
  224. if isinstance(item[0], HikkaException)
  225. and (not item[1] or item[1] == client_id or self.force_send_all)
  226. ]
  227. for client_id in self._mods
  228. }
  229. for client_id, exceptions in self._exc_queue.items():
  230. for exc in exceptions:
  231. await exc
  232. self.tg_buff = []
  233. for client_id in self._mods:
  234. if client_id not in self._queue:
  235. continue
  236. if len(self._queue[client_id]) > 5:
  237. logfile = io.BytesIO("".join(self._queue[client_id]).encode("utf-8"))
  238. logfile.name = "hikka-logs.txt"
  239. logfile.seek(0)
  240. await self._mods[client_id].inline.bot.send_document(
  241. self._mods[client_id]._logchat,
  242. logfile,
  243. caption=(
  244. "<b>🧳 Journals are too big to be sent as separate messages</b>"
  245. ),
  246. )
  247. self._queue[client_id] = []
  248. continue
  249. while self._queue[client_id]:
  250. if chunk := self._queue[client_id].pop(0):
  251. asyncio.ensure_future(
  252. self._mods[client_id].inline.bot.send_message(
  253. self._mods[client_id]._logchat,
  254. f"<code>{chunk}</code>",
  255. disable_notification=True,
  256. )
  257. )
  258. def emit(self, record: logging.LogRecord):
  259. try:
  260. caller = next(
  261. (
  262. frame_info.frame.f_locals["_hikka_client_id_logging_tag"]
  263. for frame_info in inspect.stack()
  264. if isinstance(
  265. getattr(getattr(frame_info, "frame", None), "f_locals", {}).get(
  266. "_hikka_client_id_logging_tag"
  267. ),
  268. int,
  269. )
  270. ),
  271. False,
  272. )
  273. if not isinstance(caller, int):
  274. caller = None
  275. except Exception:
  276. caller = None
  277. record.hikka_caller = caller
  278. if record.levelno >= 20:
  279. if record.exc_info:
  280. logging.debug(record.__dict__)
  281. self.tg_buff += [
  282. (
  283. HikkaException.from_exc_info(
  284. *record.exc_info,
  285. stack=record.__dict__.get("stack", None),
  286. ),
  287. caller,
  288. )
  289. ]
  290. else:
  291. self.tg_buff += [
  292. (
  293. _tg_formatter.format(record),
  294. caller,
  295. )
  296. ]
  297. if len(self.buffer) + len(self.handledbuffer) >= self.capacity:
  298. if self.handledbuffer:
  299. del self.handledbuffer[0]
  300. else:
  301. del self.buffer[0]
  302. self.buffer.append(record)
  303. if record.levelno >= self.lvl >= 0:
  304. self.acquire()
  305. try:
  306. for precord in self.buffer:
  307. for target in self.targets:
  308. if record.levelno >= target.level:
  309. target.handle(precord)
  310. self.handledbuffer = (
  311. self.handledbuffer[-(self.capacity - len(self.buffer)) :]
  312. + self.buffer
  313. )
  314. self.buffer = []
  315. finally:
  316. self.release()
  317. _main_formatter = logging.Formatter(
  318. fmt="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
  319. datefmt="%Y-%m-%d %H:%M:%S",
  320. style="%",
  321. )
  322. _tg_formatter = logging.Formatter(
  323. fmt="[%(levelname)s] %(name)s: %(message)s\n",
  324. datefmt=None,
  325. style="%",
  326. )
  327. rotating_handler = RotatingFileHandler(
  328. filename="hikka.log",
  329. mode="a",
  330. maxBytes=10 * 1024 * 1024,
  331. backupCount=1,
  332. encoding="utf-8",
  333. delay=0,
  334. )
  335. rotating_handler.setFormatter(_main_formatter)
  336. def init():
  337. handler = logging.StreamHandler()
  338. handler.setLevel(logging.INFO)
  339. handler.setFormatter(_main_formatter)
  340. logging.getLogger().handlers = []
  341. logging.getLogger().addHandler(
  342. TelegramLogsHandler((handler, rotating_handler), 7000)
  343. )
  344. logging.getLogger().setLevel(logging.NOTSET)
  345. logging.getLogger("telethon").setLevel(logging.WARNING)
  346. logging.getLogger("matplotlib").setLevel(logging.WARNING)
  347. logging.getLogger("aiohttp").setLevel(logging.WARNING)
  348. logging.getLogger("aiogram").setLevel(logging.WARNING)
  349. logging.captureWarnings(True)