1
|
import inspect
|
2
|
import logging
|
3
|
from logging import handlers
|
4
|
import os
|
5
|
from pathlib import Path
|
6
|
|
7
|
from src.config.configuration import Configuration, LOG_LEVEL_MAPPING
|
8
|
from src.constants import LOG_NAME, LOG_DIR, LOG_FILENAME, LOG_FORMAT
|
9
|
from src.utils.file_anchor import FileAnchor
|
10
|
|
11
|
|
12
|
def configure_logging(config: Configuration):
|
13
|
if not os.path.exists(FileAnchor(config.root_dir, LOG_DIR).shortest_relative_path()):
|
14
|
os.makedirs(FileAnchor(config.root_dir, LOG_DIR).shortest_relative_path())
|
15
|
|
16
|
handler = logging.handlers.TimedRotatingFileHandler(
|
17
|
os.path.join(FileAnchor(config.root_dir, LOG_DIR).shortest_relative_path(), LOG_FILENAME),
|
18
|
when='H', interval=1)
|
19
|
formatter = logging.Formatter(LOG_FORMAT)
|
20
|
handler.setFormatter(formatter)
|
21
|
|
22
|
# set log level based on config file
|
23
|
app_logger = logging.getLogger(LOG_NAME)
|
24
|
app_logger.setLevel(LOG_LEVEL_MAPPING.get(config.log_level, logging.DEBUG))
|
25
|
|
26
|
app_logger.addHandler(handler)
|
27
|
|
28
|
log = logging.getLogger('werkzeug')
|
29
|
log.disabled = True
|
30
|
|
31
|
|
32
|
class Logger:
|
33
|
|
34
|
@staticmethod
|
35
|
def get_names():
|
36
|
stack = inspect.stack()
|
37
|
|
38
|
file_name = inspect.getmodule(inspect.stack()[2][0]).__file__
|
39
|
class_name = ""
|
40
|
if "self" in stack[2][0].f_locals:
|
41
|
class_name = stack[2][0].f_locals["self"].__class__.__name__ + "."
|
42
|
function_name = stack[2][0].f_code.co_name
|
43
|
|
44
|
return file_name, class_name, function_name
|
45
|
|
46
|
@staticmethod
|
47
|
def debug(message: str):
|
48
|
names = Logger.get_names()
|
49
|
app_logger = logging.getLogger(LOG_NAME)
|
50
|
app_logger.debug(f'{Path(names[0]).name}[{names[1]}{names[2]}()]: {message}')
|
51
|
|
52
|
@staticmethod
|
53
|
def info(message: str):
|
54
|
names = Logger.get_names()
|
55
|
app_logger = logging.getLogger(LOG_NAME)
|
56
|
app_logger.info(f'{Path(names[0]).name}[{names[1]}{names[2]}()]: {message}')
|
57
|
|
58
|
@staticmethod
|
59
|
def warning(message: str):
|
60
|
names = Logger.get_names()
|
61
|
app_logger = logging.getLogger(LOG_NAME)
|
62
|
app_logger.warning(f'{Path(names[0]).name}[{names[1]}{names[2]}()]: {message}')
|
63
|
|
64
|
@staticmethod
|
65
|
def error(message: str):
|
66
|
names = Logger.get_names()
|
67
|
app_logger = logging.getLogger(LOG_NAME)
|
68
|
app_logger.error(f'{Path(names[0]).name}[{names[1]}.{names[2]}()]: {message}')
|
69
|
|
70
|
@staticmethod
|
71
|
def critical(message: str):
|
72
|
names = Logger.get_names()
|
73
|
app_logger = logging.getLogger(LOG_NAME)
|
74
|
app_logger.critical(f'{Path(names[0]).name}[{names[1]}.{names[2]}()]: {message}')
|