赞
踩
本方案可以个性化定制,以及完美的解决重复打印问题,所有情况都适用!!!
多进程用logging经常会重复打印…网上很多解决办法试了都不好使,索性自己写得了。logging的颜色配置还需要下载color模块,突然发现print就支持颜色打印,然后sys模块又支持读取函数调用的行数和代码文件读取,这不就很简单了么。
基于sys和print设计的logger
import datetime
import sys
class Logger:
@classmethod
def debug(cls, msg):
ISOTIMEFORMAT = '%Y-%m-%d %H:%M:%S'
theTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
path = sys._getframe(1).f_code.co_filename.split("/")[-1]
line = sys._getframe(1).f_lineno
print("\033[1;35m [DEBUG]--> {}:{} {} {} \033[0m".format(path, line, theTime, msg))
@classmethod
def info(cls, msg):
ISOTIMEFORMAT = '%Y-%m-%d %H:%M:%S'
theTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
path = sys._getframe(1).f_code.co_filename.split("/")[-1]
line = sys._getframe(1).f_lineno
print("\033[1;36m [INFO]--> {}:{} {} {} \033[0m".format(path, line, theTime, msg))
@classmethod
def error(cls, msg):
ISOTIMEFORMAT = '%Y-%m-%d %H:%M:%S'
theTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
path = sys._getframe(1).f_code.co_filename.split("/")[-1]
line = sys._getframe(1).f_lineno
print("\033[1;34m [ERROR]--> {}:{} {} {} \033[0m".format(path, line, theTime, msg))
@classmethod
def warning(cls, msg):
ISOTIMEFORMAT = '%Y-%m-%d %H:%M:%S'
theTime = datetime.datetime.now().strftime(ISOTIMEFORMAT)
path = sys._getframe(1).f_code.co_filename.split("/")[-1]
line = sys._getframe(1).f_lineno
print("\033[1;33m [WARNING]--> {}:{} {} {} \033[0m".format(path, line, theTime, msg))
Logger.debug("debug")
Logger.info("info")
Logger.error("error")
Logger.warning("warning")
效果:
一个demo,可以自己优化显示的效果~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。