全国多地国家A级景点暑期免门票 包括厦门鼓浪屿主要景区、青岛崂山风景区等
6月19日,厦门市文化和旅游局发布消息,即日起至8月31日,8家收费国有A级景区对市民、游客实行免门票开放,包括鼓浪屿上的主要景区。北京青
我相信每一个开发者都有打印日志的习惯,好看的日志可以加快调试的速度,可以更好的了解程序中发生的事情。本文分享一个技巧,可以让 Python 在控制台输出彩色的日志。
(资料图片仅供参考)
pipinstallcoloredlogs使用
首先,和正常打印日志一样,我们创建一个 logger
logging.basicConfig()logger=logging.getLogger(name="mylogger")
然后,把 logger 安装到 coloredlogs:
coloredlogs.install(logger=logger)logger.propagate=False
logger.propagate = False确保 coloredlogs 不会将我们的日志事件传递给根 logger,这可以防止我们重复记录每个事件。
我们想为我们的控制台输出添加一些样式,可以在这里定义:
coloredFormatter=coloredlogs.ColoredFormatter(fmt="[%(name)s]%(asctime)s%(funcName)s%(lineno)-3d%(message)s",level_styles=dict(debug=dict(color="white"),info=dict(color="blue"),warning=dict(color="yellow",bright=True),error=dict(color="red",bold=True,bright=True),critical=dict(color="black",bold=True,background="red"),),field_styles=dict(name=dict(color="white"),asctime=dict(color="white"),funcName=dict(color="white"),lineno=dict(color="white"),))
接下来就和正常使用日志一样了,配置一个流处理器,让日志显示在控制台:
ch=logging.StreamHandler(stream=sys.stdout)ch.setFormatter(fmt=coloredFormatter)logger.addHandler(hdlr=ch)logger.setLevel(level=logging.DEBUG)
接下来就可以输入日志信息了:
logger.debug(msg="thisisadebugmessage")logger.info(msg="thisisaninfomessage")logger.warning(msg="thisisawarningmessage")logger.error(msg="thisisanerrormessage")logger.critical(msg="thisisacriticalmessage")
效果图如下:
完整代码如下:
importloggingimportcoloredlogsimportsys##配置loggerlogging.basicConfig()logger=logging.getLogger(name="mylogger")coloredlogs.install(logger=logger)logger.propagate=False##配置颜色coloredFormatter=coloredlogs.ColoredFormatter(fmt="[%(name)s]%(asctime)s%(funcName)s%(lineno)-3d%(message)s",level_styles=dict(debug=dict(color="white"),info=dict(color="blue"),warning=dict(color="yellow",bright=True),error=dict(color="red",bold=True,bright=True),critical=dict(color="black",bold=True,background="red"),),field_styles=dict(name=dict(color="white"),asctime=dict(color="white"),funcName=dict(color="white"),lineno=dict(color="white"),))##配置StreamHandlerch=logging.StreamHandler(stream=sys.stdout)ch.setFormatter(fmt=coloredFormatter)logger.addHandler(hdlr=ch)logger.setLevel(level=logging.DEBUG)##outputlogger.debug(msg="thisisadebugmessage")logger.info(msg="thisisaninfomessage")logger.warning(msg="thisisawarningmessage")logger.error(msg="thisisanerrormessage")logger.critical(msg="thisisacriticalmessage")最后的话
本文分享了一种输出彩色日志的方法,感觉不错的话,请分享给身边的程序员们,祝编码愉快。
标签: 正常使用
6月19日,厦门市文化和旅游局发布消息,即日起至8月31日,8家收费国有A级景区对市民、游客实行免门票开放,包括鼓浪屿上的主要景区。北京青
图①:山西临汾经济技术开发区兴荣供应链有限公司的货车整装待发。资料图片 图②:司机王勇平驾驶货车行驶在
2022年北京冬奥会的筹办过程,为中国冰雪运动发展提供了巨大动力。科技创新,成为中国冰雪运动前进道路上嘹亮的号角。在科学技术部社会发展
游客在银川市黄河横城旅游度假区观看花灯展(2月5日摄)。春节假期,“2022黄河横城冰雪彩灯艺术节”在宁夏银川市
新华社香港2月6日电题:狮子山下的舞狮人新华社记者韦骅“左眼精,右眼灵,红光万象,富贵繁荣!”“口食八方财,
正在进行围封或强制检测的葵涌邨居民在登记(资料照片)。新华社发新华社香港2月6日电 题:凝聚香港社会共克时艰
2月6日,航拍青海省西宁市雪后美景。受较强冷空气影响,2月5日至6日,青海迎来大范围降雪天气过程,古城西宁银装
[ 相关新闻 ]