Python教程

Python日志封装可多模块调用

本文主要是介绍Python日志封装可多模块调用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: wjh
# @Date  : 2019/06/20 15:00
# @Desc  : 封装log日志文件
 
import logging
import logging.handlers
import os
import time
 
class logs(object):
    def __init__(self,level,logger=None):
        self.logger = logger
        self.logger = logging.getLogger(logger)
        # 设置输出的等级
        LEVELS = {'NOSET':    logging.NOTSET,
                  'DEBUG':    logging.DEBUG,
                  'INFO':     logging.INFO,
                  'WARNING':  logging.WARNING,
                  'ERROR':    logging.ERROR,
                  'CRITICAL': logging.CRITICAL}
        # 创建文件目录
        logs_dir="../log"
        if os.path.exists(logs_dir) and os.path.isdir(logs_dir):
            pass
        else:
            os.mkdir(logs_dir)
        # 修改log保存位置
        timestamp=time.strftime("%Y-%m-%d",time.localtime())
        logfilename= "log-%s.log" % timestamp
        logfilepath=os.path.join(logs_dir,logfilename)
        rotatingFileHandler = logging.handlers.RotatingFileHandler(filename =logfilepath,
                                                                   maxBytes = 1024 * 1024 * 50,
                                                                   backupCount = 500)
        # 设置输出格式
        formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
        rotatingFileHandler.setFormatter(formatter)
        # 控制台句柄
        console = logging.StreamHandler()
        Level = LEVELS.get(level)
        console.setLevel(Level)
        console.setFormatter(formatter)
        # 添加内容到日志句柄中
        self.logger.addHandler(rotatingFileHandler)
        self.logger.addHandler(console)
        self.logger.setLevel(Level)
        # 解决重复日志问题
        self.logger.handlers=self.logger.handlers[:1]

    def info(self, message):
        self.logger.info(message)
    def debug(self, message):
        self.logger.debug(message)
    def warning(self, message):
        self.logger.warning(message)
    def error(self, message):
        self.logger.error(message)
if __name__ == '__main__':
    log_ = logs(os.path.basename(__file__).split(".")[0])
    log_.debug('总账本剩余量:{0}'.format(real_balance1))

这篇关于Python日志封装可多模块调用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!