1
|
|
|
""" |
2
|
|
|
|
3
|
|
|
Info about logging levels: |
4
|
|
|
|
5
|
|
|
DEBUG: Detailed information, typically of interest only when diagnosing problems. |
6
|
|
|
|
7
|
|
|
INFO: Confirmation that things are working as expected. |
8
|
|
|
|
9
|
|
|
WARNING: An indication that something unexpected happened, or indicative of some |
10
|
|
|
problem in the near future (e.g. ‘disk space low’). The software is still working |
11
|
|
|
as expected. |
12
|
|
|
|
13
|
|
|
ERROR: Due to a more serious problem, the software has not been able to perform |
14
|
|
|
some function. |
15
|
|
|
|
16
|
|
|
CRITICAL: A serious error, indicating that the program itself may be unable to |
17
|
|
|
continue running. |
18
|
|
|
|
19
|
|
|
""" |
20
|
|
|
|
21
|
|
|
import logging |
22
|
|
|
from logging import Handler |
23
|
|
|
from logging import LogRecord |
24
|
|
|
from logging import Formatter |
25
|
|
|
import os |
26
|
|
|
from datetime import datetime, timezone, timedelta |
27
|
|
|
|
28
|
|
|
import requests |
29
|
|
|
|
30
|
|
|
|
31
|
|
|
class BaseFormatter(Formatter): |
32
|
|
|
def format(self, record: LogRecord) -> str: |
33
|
|
|
message = record.msg |
34
|
|
|
levelname = record.levelname |
35
|
|
|
module = record.module |
36
|
|
|
timestamp = datetime.utcfromtimestamp(record.created) |
37
|
|
|
ts = ( |
38
|
|
|
timestamp.replace(tzinfo=timezone.utc) |
39
|
|
|
.astimezone(tz=timezone(timedelta(hours=3))) |
40
|
|
|
.strftime("%d.%m.%Y %H:%M:%S") |
41
|
|
|
) |
42
|
|
|
fmt = f"[{levelname}] ({module}): {ts} {message}" |
43
|
|
|
if record.exc_info: |
44
|
|
|
fmt += f"\n{record.exc_info[1].__repr__()}" |
45
|
|
|
return fmt |
46
|
|
|
|
47
|
|
|
|
48
|
|
|
class Logger: |
49
|
|
|
def __init__(self): |
50
|
|
|
self.logger = logging.getLogger(__name__) |
51
|
|
|
if self.logger.hasHandlers(): |
52
|
|
|
self.logger.handlers.clear() |
53
|
|
|
|
54
|
|
|
def init(self): |
55
|
|
|
self.logger.setLevel("INFO") |
56
|
|
|
console = logging.StreamHandler() |
57
|
|
|
formatter = BaseFormatter() |
58
|
|
|
console.setFormatter(formatter) |
59
|
|
|
self.logger.addHandler(console) |
60
|
|
|
return self.logger |
61
|
|
|
|