Total Complexity | 6 |
Total Lines | 52 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | import logging |
||
2 | from logging import Handler |
||
3 | from logging import LogRecord |
||
4 | from logging import Formatter |
||
5 | import os |
||
6 | from datetime import datetime, timezone, timedelta |
||
7 | |||
8 | import requests |
||
9 | |||
10 | |||
11 | class TelegramHandler(Handler): |
||
12 | def emit(self, record: LogRecord) -> None: |
||
13 | log_entry = self.format(record) |
||
14 | token = os.environ["TG_TOKEN"] |
||
15 | chat_ids = os.environ["TG_CHATS"].split(",") |
||
16 | notifications = False |
||
17 | if record.levelno < 30: |
||
18 | notifications = True |
||
19 | for chat in chat_ids: |
||
20 | requests.get( |
||
21 | f"https://api.telegram.org/bot{token}/sendMessage?chat_id=" |
||
22 | f"{chat}&text" |
||
23 | f"={log_entry}&parse_mode=markdown&disable_notification={notifications}" |
||
24 | ) |
||
25 | |||
26 | |||
27 | class TelegramFormatter(Formatter): |
||
28 | def format(self, record: LogRecord) -> str: |
||
29 | message = record.msg |
||
30 | levelname = record.levelname |
||
31 | timestamp = datetime.utcfromtimestamp(record.created) |
||
32 | ts = ( |
||
33 | timestamp.replace(tzinfo=timezone.utc) |
||
34 | .astimezone(tz=timezone(timedelta(hours=3))) |
||
35 | .strftime("%d.%m.%Y %H:%M:%S") |
||
36 | ) |
||
37 | log = f"[{levelname}]: {ts}\n{message}" |
||
38 | if record.exc_info: |
||
39 | log += f"\n{record.exc_info[1].__repr__()}" |
||
40 | return log |
||
41 | |||
42 | |||
43 | def init_logger(): |
||
44 | logger = logging.getLogger() |
||
45 | logger.setLevel("INFO") |
||
46 | handler = TelegramHandler() |
||
47 | formatter = TelegramFormatter() |
||
48 | handler.setFormatter(formatter) |
||
49 | logger.addHandler(handler) |
||
50 | |||
51 | return logger |
||
52 |