-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog.py
77 lines (62 loc) · 2.24 KB
/
log.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
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
# _*_ coding:utf-8 _*_
import logging
import logging.handlers
import logging.config
import os
import configparser
import re
class CustomLogger:
def __init__(self, config_path):
self.load_conf(config_path)
# loading log config
logging.config.fileConfig('logger_config.conf')
# Create a logger
self.logger = logging.getLogger()
@staticmethod
def load_conf(config_path):
# Read the configuration file
config = configparser.ConfigParser()
config.read(config_path)
# Get fileHandler conf
file_handler = config['handlers']['keys']
if 'fileHandler' in file_handler:
handler_file_handler_conf = \
config.get(f'handler_fileHandler', 'args')
CustomLogger.path_check(handler_file_handler_conf)
@staticmethod
def path_check(handler_file_handler_conf):
# Check if the path where the log files are stored exists.
log_file_path, file_open_mode = \
tuple(handler_file_handler_conf.strip('()').split(','))
log_file_path = re.sub(r"['\"]", "", log_file_path)
log_file_dirname = os.path.dirname(log_file_path)
if not os.path.exists(log_file_dirname):
os.makedirs(log_file_dirname)
def info(self, message):
self.logger.info(message)
def debug(self, message):
self.logger.debug(message)
def warning(self, message):
self.logger.warning(message)
def error(self, message):
self.logger.error(message)
def critical(self, message):
self.logger.critical(message)
def exception(self, message):
self.logger.exception(message)
# usage example
if __name__ == "__main__":
# path to the configuration file
path = './logger_config.conf'
# create an instance of CustomLogger, passing the configuration file path
logger = CustomLogger(path)
# output log messages
logger.info('this is an info message.')
logger.debug('this is a debug message.')
logger.warning('this is a warning message.')
logger.error('this is an error message.')
logger.critical('this is a critical message.')
try:
1/0
except ZeroDivisionError as e:
logger.exception('this is a exception message.')