log.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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 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. ) -> "HikkaException":
  47. def to_hashable(dictionary: dict) -> dict:
  48. dictionary = dictionary.copy()
  49. for key, value in dictionary.items():
  50. if isinstance(value, dict):
  51. if (
  52. getattr(getattr(value, "__class__", None), "__name__", None)
  53. == "Database"
  54. ):
  55. dictionary[key] = "<Database>"
  56. if isinstance(value, telethon.TelegramClient):
  57. dictionary[key] = "<TelegramClient>"
  58. dictionary[key] = to_hashable(value)
  59. else:
  60. try:
  61. json.dumps([value])
  62. except Exception:
  63. dictionary[key] = str(value)
  64. return dictionary
  65. full_stack = traceback.format_exc().replace(
  66. "Traceback (most recent call last):\n", ""
  67. )
  68. line_regex = r' File "(.*?)", line ([0-9]+), in (.+)'
  69. def format_line(line: str) -> str:
  70. filename_, lineno_, name_ = re.search(line_regex, line).groups()
  71. with contextlib.suppress(Exception):
  72. filename_ = os.path.basename(filename_)
  73. return (
  74. f"👉 <code>{utils.escape_html(filename_)}:{lineno_}</code> <b>in</b>"
  75. f" <code>{utils.escape_html(name_)}</code>"
  76. )
  77. filename, lineno, name = next(
  78. (
  79. re.search(line_regex, line).groups()
  80. for line in full_stack.splitlines()
  81. if re.search(line_regex, line)
  82. ),
  83. (None, None, None),
  84. )
  85. line = next(
  86. (line for line in full_stack.splitlines() if line.startswith(" ")), ""
  87. )
  88. full_stack = "\n".join(
  89. [
  90. format_line(line)
  91. if re.search(line_regex, line)
  92. else f"<code>{utils.escape_html(line)}</code>"
  93. for line in full_stack.splitlines()
  94. ]
  95. )
  96. with contextlib.suppress(Exception):
  97. filename = os.path.basename(filename)
  98. return HikkaException(
  99. message=(
  100. "<b>🚫 Error!</b>\n<b>🗄 Where:</b>"
  101. f" <code>{utils.escape_html(filename)}:{lineno}</code><b>"
  102. f" in </b><code>{utils.escape_html(name)}</code>\n😵"
  103. f" <code>{utils.escape_html(line)}</code>"
  104. " 👈\n<b>❓ What:</b>"
  105. f" <code>{utils.escape_html(''.join(traceback.format_exception_only(exc_type, exc_value)).strip())}</code>"
  106. ),
  107. local_vars=(
  108. f"<code>{utils.escape_html(json.dumps(to_hashable(tb.tb_frame.f_locals), indent=4))}</code>"
  109. ),
  110. full_stack=full_stack,
  111. )
  112. class TelegramLogsHandler(logging.Handler):
  113. """
  114. Keeps 2 buffers.
  115. One for dispatched messages.
  116. One for unused messages.
  117. When the length of the 2 together is 100
  118. truncate to make them 100 together,
  119. first trimming handled then unused.
  120. """
  121. def __init__(self, targets: list, capacity: int):
  122. super().__init__(0)
  123. self.targets = targets
  124. self.capacity = capacity
  125. self.buffer = []
  126. self.handledbuffer = []
  127. self.lvl = logging.NOTSET # Default loglevel
  128. self._queue = []
  129. self.tg_buff = []
  130. self._mods = {}
  131. self.force_send_all = False
  132. def install_tg_log(self, mod: Module):
  133. if getattr(self, "_task", False):
  134. self._task.cancel()
  135. self._mods[mod.tg_id] = mod
  136. self._task = asyncio.ensure_future(self.queue_poller())
  137. async def queue_poller(self):
  138. while True:
  139. await self.sender()
  140. await asyncio.sleep(3)
  141. def setLevel(self, level: int):
  142. self.lvl = level
  143. def dump(self):
  144. """Return a list of logging entries"""
  145. return self.handledbuffer + self.buffer
  146. def dumps(self, lvl: Optional[int] = 0, client_id: Optional[int] = None) -> list:
  147. """Return all entries of minimum level as list of strings"""
  148. return [
  149. self.targets[0].format(record)
  150. for record in (self.buffer + self.handledbuffer)
  151. if record.levelno >= lvl
  152. and (not record.hikka_caller or client_id == record.hikka_caller)
  153. ]
  154. async def _show_full_stack(
  155. self,
  156. call: BotInlineCall,
  157. bot: "aiogram.Bot", # type: ignore
  158. item: HikkaException,
  159. ):
  160. chunks = (
  161. item.message
  162. + "\n\n<b>🦝 Locals:</b>\n"
  163. + item.local_vars
  164. + "\n\n"
  165. + "<b>🪐 Full stack:</b>\n"
  166. + item.full_stack
  167. )
  168. chunks = list(utils.smart_split(*telethon.extensions.html.parse(chunks), 4096))
  169. await call.edit(chunks[0])
  170. for chunk in chunks[1:]:
  171. await bot.send_message(chat_id=call.chat_id, text=chunk)
  172. async def sender(self):
  173. self._queue = {
  174. client_id: utils.chunks(
  175. utils.escape_html(
  176. "".join(
  177. [
  178. item[0]
  179. for item in self.tg_buff
  180. if isinstance(item[0], str)
  181. and (
  182. not item[1]
  183. or item[1] == client_id
  184. or self.force_send_all
  185. )
  186. ]
  187. )
  188. ),
  189. 4096,
  190. )
  191. for client_id in self._mods
  192. }
  193. self._exc_queue = {
  194. client_id: [
  195. self._mods[client_id].inline.bot.send_message(
  196. self._mods[client_id]._logchat,
  197. item[0].message,
  198. reply_markup=self._mods[client_id].inline.generate_markup(
  199. {
  200. "text": "🪐 Full stack",
  201. "callback": self._show_full_stack,
  202. "args": (
  203. self._mods[client_id].inline.bot,
  204. item[0],
  205. ),
  206. }
  207. ),
  208. )
  209. for item in self.tg_buff
  210. if isinstance(item[0], HikkaException)
  211. and (not item[1] or item[1] == client_id or self.force_send_all)
  212. ]
  213. for client_id in self._mods
  214. }
  215. for client_id, exceptions in self._exc_queue.items():
  216. for exc in exceptions:
  217. await exc
  218. self.tg_buff = []
  219. for client_id in self._mods:
  220. if client_id not in self._queue:
  221. continue
  222. if len(self._queue[client_id]) > 5:
  223. logfile = io.BytesIO("".join(self._queue[client_id]).encode("utf-8"))
  224. logfile.name = "hikka-logs.txt"
  225. logfile.seek(0)
  226. await self._mods[client_id].inline.bot.send_document(
  227. self._mods[client_id]._logchat,
  228. logfile,
  229. caption=(
  230. "<b>🧳 Journals are too big to be sent as separate messages</b>"
  231. ),
  232. )
  233. self._queue[client_id] = []
  234. continue
  235. while self._queue[client_id]:
  236. if chunk := self._queue[client_id].pop(0):
  237. asyncio.ensure_future(
  238. self._mods[client_id].inline.bot.send_message(
  239. self._mods[client_id]._logchat,
  240. f"<code>{chunk}</code>",
  241. disable_notification=True,
  242. )
  243. )
  244. def emit(self, record: logging.LogRecord):
  245. try:
  246. caller = next(
  247. (
  248. frame_info.frame.f_locals["_hikka_client_id_logging_tag"]
  249. for frame_info in inspect.stack()
  250. if isinstance(
  251. getattr(getattr(frame_info, "frame", None), "f_locals", {}).get(
  252. "_hikka_client_id_logging_tag"
  253. ),
  254. int,
  255. )
  256. ),
  257. False,
  258. )
  259. if not isinstance(caller, int):
  260. caller = None
  261. except Exception:
  262. caller = None
  263. record.hikka_caller = caller
  264. if record.levelno >= 20:
  265. if record.exc_info:
  266. self.tg_buff += [
  267. (
  268. HikkaException.from_exc_info(*record.exc_info),
  269. caller,
  270. )
  271. ]
  272. else:
  273. self.tg_buff += [
  274. (
  275. _tg_formatter.format(record),
  276. caller,
  277. )
  278. ]
  279. if len(self.buffer) + len(self.handledbuffer) >= self.capacity:
  280. if self.handledbuffer:
  281. del self.handledbuffer[0]
  282. else:
  283. del self.buffer[0]
  284. self.buffer.append(record)
  285. if record.levelno >= self.lvl >= 0:
  286. self.acquire()
  287. try:
  288. for precord in self.buffer:
  289. for target in self.targets:
  290. if record.levelno >= target.level:
  291. target.handle(precord)
  292. self.handledbuffer = (
  293. self.handledbuffer[-(self.capacity - len(self.buffer)) :]
  294. + self.buffer
  295. )
  296. self.buffer = []
  297. finally:
  298. self.release()
  299. _main_formatter = logging.Formatter(
  300. fmt="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
  301. datefmt="%Y-%m-%d %H:%M:%S",
  302. style="%",
  303. )
  304. _tg_formatter = logging.Formatter(
  305. fmt="[%(levelname)s] %(name)s: %(message)s\n",
  306. datefmt=None,
  307. style="%",
  308. )
  309. rotating_handler = RotatingFileHandler(
  310. filename="hikka.log",
  311. mode="a",
  312. maxBytes=10 * 1024 * 1024,
  313. backupCount=1,
  314. encoding="utf-8",
  315. delay=0,
  316. )
  317. rotating_handler.setFormatter(_main_formatter)
  318. def init():
  319. handler = logging.StreamHandler()
  320. handler.setLevel(logging.INFO)
  321. handler.setFormatter(_main_formatter)
  322. logging.getLogger().handlers = []
  323. logging.getLogger().addHandler(
  324. TelegramLogsHandler((handler, rotating_handler), 7000)
  325. )
  326. logging.getLogger().setLevel(logging.NOTSET)
  327. logging.getLogger("telethon").setLevel(logging.WARNING)
  328. logging.getLogger("matplotlib").setLevel(logging.WARNING)
  329. logging.getLogger("aiohttp").setLevel(logging.WARNING)
  330. logging.getLogger("aiogram").setLevel(logging.WARNING)
  331. logging.captureWarnings(True)