-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.py
34 lines (26 loc) · 978 Bytes
/
logger.py
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
import os
import logging
from pathlib import Path
class ServiceLogger:
def __init__(self, name, file, loglevel='DEBUG'):
p = str(Path(file).parent) + '/logs/'
i = 0
while True:
if not os.path.exists(p):
i = i + 1
p = str(Path(file).parents[i]) + '/logs/'
else:
self.dirpath = p
break
self.logger = self.__get_logger(loglevel, name)
# private method
def __get_logger(self, loglevel, name=__name__, encoding='utf-8'):
log = logging.getLogger(name)
level = logging.getLevelName(loglevel)
log.setLevel(level)
formatter = logging.Formatter('[%(asctime)s] %(filename)s:%(lineno)d %(levelname)-1s %(message)s')
file_name = self.dirpath + name + '.log'
fh = logging.FileHandler(file_name, mode='a', encoding=encoding)
fh.setFormatter(formatter)
log.addHandler(fh)
return log