generatelog.py
1.8 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
# -*- coding: utf-8 -*-
# @Time : 2021/1/19 9:17
# @Author : Young Lee
# @Email : young_lee2017@163.com
import logging
import os
import configparser
import re
from logging.config import fileConfig
def generate_log(logfile_name='testing.log', logfile_path=None, config_path=None, logger_name='simpleLog'):
"""动态复用日志配置文件,更具需要更换日志存储路径
:param logfile_name: 日志名称,logfile_path为None时logfile_name生效
:param logfile_path: 日志存储路径,为空时存储在generatelog.py同目录下的testing.log中
:param config_path: 日志配置文件路径,为空时为generatelog.py同目录下的logging.conf文件
:param logger_name: 要使用的日志器名称
:return: logger对象
"""
current_dir = os.path.dirname(os.path.abspath(__file__))
if logfile_path is None:
logfile_path = os.path.join(current_dir, logfile_name)
logfile_path_str = f"r'{logfile_path}'"
if config_path is None:
config_path = os.path.join(current_dir, 'logging.conf')
config = configparser.ConfigParser()
config.read(config_path)
for sec in config.sections():
if not re.match('handler_.*', sec):
continue
if 'args' not in config.options(sec):
continue
cfg_args = config.get(sec, 'args').replace('LogFilePath', logfile_path_str)
config.set(sec, 'args', cfg_args)
fileConfig(config)
logger = logging.getLogger(logger_name)
return logger
if __name__ == '__main__':
import time
logger = generate_log('test_2021.log')
while True:
logger.debug('debug message')
logger.info('info message')
logger.warning('warning message')
logger.error('error message')
logger.critical('critical message')
time.sleep(1)