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))

上一篇:深入分析 Java I/O 的工作机制--转载


下一篇:【已解决】Java HotSpot(TM)64-Bit Server VM warning: Cannot open file logs/gc.log due to Permission denied