前言
成都創(chuàng)新互聯(lián)堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站制作、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的濱城網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!今天就簡(jiǎn)單的對(duì)日志做個(gè)封裝,實(shí)際工作中直接拿去用吧
方法1
""" ------------------------------------ @Time : 2019/5/22 8:12 @Auth : linux超 @File : logfile.py @IDE : PyCharm @Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error! ------------------------------------ """ import logging class Log(object): def __init__(self, name=__name__, path='mylog.log', level='DEBUG'): self.__name = name self.__path = path self.__level = level self.__logger = logging.getLogger(self.__name) self.__logger.setLevel(self.__level) def __ini_handler(self): """初始化handler""" stream_handler = logging.StreamHandler() file_handler = logging.FileHandler(self.__path, encoding='utf-8') return stream_handler, file_handler def __set_handler(self, stream_handler, file_handler, level='DEBUG'): """設(shè)置handler級(jí)別并添加到logger收集器""" stream_handler.setLevel(level) file_handler.setLevel(level) self.__logger.addHandler(stream_handler) self.__logger.addHandler(file_handler) def __set_formatter(self, stream_handler, file_handler): """設(shè)置日志輸出格式""" formatter = logging.Formatter('%(asctime)s-%(name)s-%(filename)s-[line:%(lineno)d]' '-%(levelname)s-[日志信息]: %(message)s', datefmt='%a, %d %b %Y %H:%M:%S') stream_handler.setFormatter(formatter) file_handler.setFormatter(formatter) def __close_handler(self, stream_handler, file_handler): """關(guān)閉handler""" stream_handler.close() file_handler.close() @property def Logger(self): """構(gòu)造收集器,返回looger""" stream_handler, file_handler = self.__ini_handler() self.__set_handler(stream_handler, file_handler) self.__set_formatter(stream_handler, file_handler) self.__close_handler(stream_handler, file_handler) return self.__logger if __name__ == '__main__': log = Log(__name__, 'file.log') logger = log.Logger logger.debug('I am a debug message') logger.info('I am a info message') logger.warning('I am a warning message') logger.error('I am a error message') logger.critical('I am a critical message')