python log封装

 1 # _*_ coding:utf-8 _*_
 2 
 3 import logging
 4 import os
 5 import sys
 6 import time
 7 
 8 log_path = os.path.dirname(sys.path[0]) + '/log_path'
 9 
10 class Log():
11     def __init__(self):
12         filename = 'test_' + time.strftime('%Y_%m_%d_%H%M%S') + '.log'   # 设置log名
13         self.logname = os.path.join(log_path, filename)
14         self.logger = logging.getLogger()
15         self.logger.setLevel(logging.DEBUG)
16         #设置日志输出格式
17         self.formatter = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s:%(lineno)d] - %(message)s')
18 
19     def output(self, level, message):
20         """
21         :param level: 日志等级
22         :param message: 日志需要打印的信息
23         :return:
24         """
25         # send logging output to a disk file
26         fh = logging.FileHandler(self.logname, 'a', encoding='utf-8')
27         fh.setLevel(logging.DEBUG)
28         fh.setFormatter(self.formatter)
29         self.logger.addHandler(fh)
30 
31         # send logging output to streams
32         ch = logging.StreamHandler()
33         ch.setLevel(logging.DEBUG)
34         ch.setFormatter(self.formatter)
35         self.logger.addHandler(ch)
36 
37         if level == 'info':
38             self.logger.info(message)
39         elif level == 'debug':
40             self.logger.debug(message)
41         elif level == 'warn':
42             self.logger.warn(message)
43         elif level == 'error':
44             self.logger.error(message)
45 
46         #防止重复打印
47         self.logger.removeHandler(fh)
48         self.logger.removeHandler(ch)
49 
50         fh.close()
51 
52     def info(self, message: object) -> object:
53         self.output('info', message)
54 
55     def debug(self, message):
56         self.output('debug', message)
57 
58     def warn(self, message):
59         self.output('warn', message)
60 
61     def error(self, message):
62         self.output('error', message)

 

posted @ 2019-04-26 14:54  MC-Blog  阅读(286)  评论(0编辑  收藏  举报