python日志模块--封装

本文详细介绍了Python的日志模块使用方法,包括如何配置日志级别、输出格式和处理器,以及如何进行模块化的日志封装,提升代码复用性和日志管理效率。
摘要由CSDN通过智能技术生成
import logging,time,os,sys

'''
使用方法:在project主目录下新建lib目录,将logger_fengzhuang.py文件复制进去

调用方式:
logger = Logger(file_or_terminal="file", level="DEBEG").getLogger()
# logger = Logger(file_or_terminal="terminal").getLogger()
# logger = Logger(file_or_terminal="all").getLogger()
logger.debug("debug")
logger.info("info")
logger.error("info")
    
    # file_or_terminal == terminal: 只打印到命令行
    # file_or_terminal == file: 只打印到日志文件
    # file_or_terminal == all: 同时打印到日志文件和命令行
    # level = CRITICAL','ERROR','WARNING','INFO','DEBUG

'''

class Logger():

    def __init__(self, file_or_terminal="file", level="ERROR"):
        self.logger = logging.getLogger()
        self.logger.setLevel(level)
        info = '''
                file_or_terminal == terminal: 只打印到命令行
                file_or_terminal == file: 只打印到日志文件
                file_or_terminal == all: 同时打印到日志文件和命令行
                level = CRITICAL','ERROR','WARNING','INFO','DEBUG
            '''
        proDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        resultPath = os.path.join(proDir, 'result')
        result_Log_Path = os.path.join(resultPath, 'Log')
        result_Html_Path = os.path.join(resultPath, 'HTML报告')
        Log_month_Dir = os.path.join(result_Log_Path, time.strftime("%Y-%m"))
        self.Log_day_log_Path = os.path.join(Log_month_Dir, time.strftime("%Y-%m-%d")+'.log')
        # 创建result文件夹及里面的日期时间文件夹、创建Log文件夹、创建"HTML报告"文件夹、当天日期命名的log文件夹(若不存在)
        for i in [resultPath, result_Log_Path, result_Html_Path, Log_month_Dir]:
            if not os.path.exists(i):
                os.mkdir(i)
        #
        # print(info)
        time.sleep(0.1)
        self.file_or_terminal = file_or_terminal


    def getLogger(self):
        fm = logging.Formatter(fmt='%(asctime)s %(filename)s[%(lineno)d] %(levelname)s %(message)s %(module)s %(funcName)s', datefmt="%Y-%m-%d %X")
        def only_file():
            fh = logging.FileHandler(os.path.join(self.Log_day_log_Path))
            fh.setFormatter(fm)
            self.logger.addHandler(fh)
            return self.logger

        def only_terminal():
            ch = logging.StreamHandler()
            ch.setFormatter(fm)
            self.logger.addHandler(ch)
            return self.logger

        def file_and_terminal():
            only_file()
            only_terminal()
            return self.logger

        choice_dict = {
            "terminal": only_terminal,
            "file": only_file,
            "all": file_and_terminal,
        }

        if choice_dict.get(self.file_or_terminal):
            return choice_dict.get(self.file_or_terminal)()
        else:
            return choice_dict.get("file")()



if __name__ == '__main__':
    # logger = Logger().getLogger()
    logger = Logger("all").getLogger()
    # logger = Logger("terminal", "INFO").getLogger()
    # logger = Logger("file", "DEBUG").getLogger()
    logger.debug("debug")
    logger.info("info")
    logger.error("info")



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值