image.png
测试
from Tools.Debug import Debug
# todo 测试
a = 10
b = 4
c = a - b
Debug.IsShowLog = True
Debug.debug(c)
Debug.info(c)
Debug.warning(c)
Debug.error(c)
Debug.fatal(c)
工具静态类,放于Tools文件夹中
import logging
# 自定义封装的log管理器,静态类
class Debug:
# 静态变量,决定是否输出log,使用方法(Debug.IsShowLog = False)
IsShowLog = True
# 不同log,对应不同等级的颜色
colorList = {
logging.INFO: '\033[01;32m%s\033[0m',
logging.DEBUG: '\033[0;30m%s\033[0m',
logging.WARNING: '\033[0;33m%s\033[0m',
logging.ERROR: '\033[0;31m%s\033[0m',
logging.FATAL: '\033[0;31m%s\033[0m',
}
@staticmethod
def printConsole(level,message):
if not Debug.IsShowLog:
return
# 获取一个logger
log = logging.getLogger()
log.setLevel(level)
# 再创建一个handler,用于输出到控制台
ch = logging.StreamHandler()
ch.setLevel(level)
# 定义handler的输出格式
color = Debug.colorList[level]
formatter = logging.Formatter(color %'%(asctime)s - %(name)s - %(levelname)s : %(message)s')
ch.setFormatter(formatter)
# 给logger添加handler
log.addHandler(ch)
# 记录一条日志
if level == logging.INFO:
log.info(message)
elif level == logging.DEBUG:
log.debug(message)
elif level == logging.WARNING:
log.warning(message)
elif level == logging.ERROR:
log.error(message)
elif level == logging.FATAL:
log.fatal(message)
log.removeHandler(ch)
@staticmethod
def debug(message):
Debug.printConsole(logging.DEBUG,message)
@staticmethod
def info(message):
Debug.printConsole(logging.INFO,message)
@staticmethod
def warning(message):
Debug.printConsole(logging.WARNING,message)
@staticmethod
def error(message):
Debug.printConsole(logging.ERROR,message)
@staticmethod
def fatal(message):
Debug.printConsole(logging.FATAL,message)