-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.py
More file actions
88 lines (66 loc) · 2.74 KB
/
logger.py
File metadata and controls
88 lines (66 loc) · 2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import os
import logging
import datetime
import inspect
class Logger(logging.Logger):
_instance = None
def __new__(cls, **kwargs):
if not len(kwargs) or 'args' not in kwargs:
return cls._instance
if cls._instance is None:
print('Creating the object')
cls._instance = super(Logger, cls).__new__(cls)
return cls._instance
def __init__(self, **kwargs):
if not len(kwargs) \
or 'args' not in kwargs :
print('There is no args parameter passed to Logger')
return
print("Initializing the log...")
args = kwargs['args']
self.__log_level = logging._nameToLevel.get(args.log_level.upper())
log_file_name = 'git_diff'
if hasattr(args, 'log_dir') and args.log_dir:
if not os.path.exists(args.log_dir):
print('Log dir does not exists. Creating directory:{}'.format(
args.log_dir))
os.makedirs(args.log_dir)
log_file_name = "{}/git_diff_{}.log".format(
args.log_dir, datetime.datetime.now().strftime("_%Y_%m_%d"))
super().__init__(log_file_name, self.__log_level)
self.fh = logging.FileHandler(log_file_name, encoding='utf-8')
self.fh.encoding='utf-8'
self.fh.setFormatter(logging.Formatter(
fmt=u'%(asctime)s.%(msecs)03d [%(levelname)-8s] %(message)s'
, datefmt="%H:%M:%S"))
self.addHandler(self.fh)
else:
super().__init__(log_file_name, self.__log_level)
self.sh = logging.StreamHandler()
self.sh.setFormatter(logging.Formatter(
fmt=u'%(asctime)s.%(msecs)03d [%(levelname)-8s] %(message)s'
, datefmt="%H:%M:%S"))
self.addHandler(self.sh)
self.debug('Logger initialized, log_level={} -- {}, file={}'.format(
self.__log_level, self.get_level_name(), log_file_name))
# logger interface
def dbg(self, info):
# if log_level > 'debug' then exit
calframe = inspect.getouterframes(inspect.currentframe(), 2)
frame = calframe[1]
file = frame.filename
current_dir = os.path.abspath(os.getcwd())
if current_dir not in file:
file = f'{current_dir}/{file}'
self.debug(
'file "{}:{}", in {}\n' \
'===> {}'.format(file, frame.lineno, frame.function, info))
def get_level_name(self) -> str:
"""
param could be self or the string value one of
'notset|debug|info|warn|error|critical'
"""
return logging.getLevelName(self.__log_level).lower()
def get_level_value(self) -> int:
return self.__log_level
log = Logger()