2. 接口自动化框架---封装log日志模块(log_handler)

 1 """
 2 日志处理器
 3 """
 4 
 5 import logging
 6 import settings
 7 
 8 
 9 def get_logger(name='WJ-test', file='WJ-test.log',
10                fmt='%(levelname)s %(asctime)s [%(filename)s-->line:%(lineno)d]:%(message)s',
11                debug=False):
12     if debug:
13         # 如果开启了调试模式
14         file_level = logging.DEBUG
15         console_level = logging.DEBUG
16     else:
17         file_level = logging.WARNING
18         console_level = logging.INFO
19 
20     logger = logging.getLogger(name)
21 
22     logger.setLevel(logging.DEBUG)   # 设置等级
23     # 2. 创建日志处理器
24     file_handler = logging.FileHandler(filename=file, encoding='utf-8')
25     file_handler.setLevel(file_level)   # 设置写入文件的日志等级
26 
27     console_handler = logging.StreamHandler()
28     console_handler.setLevel(console_level)   # 设置控制台输出日志的等级
29 
30     # 3. 创建格式化器
31     formatter = logging.Formatter(fmt=fmt)
32 
33     # 4. 把格式化器添加到日志处理器上
34     file_handler.setFormatter(formatter)
35     console_handler.setFormatter(formatter)
36 
37     # 5. 把日志处理器添加到日志器
38     logger.addHandler(file_handler)
39     logger.addHandler(console_handler)
40     return logger
41 
42 
43 logger = get_logger(**settings.LOG_CONFIG)
44 
45 print(logger.handlers)
46 print(id(logger))
47 logger.info('this is a info---1')
48 log = get_logger()
49 print(id(log))
50 print(log.handlers)
51 log.info('this is a info')

 

posted @ 2022-03-21 11:55  WJ-HAHA  阅读(212)  评论(0编辑  收藏  举报