当前位置:首页 > 科技  > 软件

为什么不推荐使用Python原生日志库?

来源: 责编: 时间:2023-11-06 17:19:10 393观看
导读包括我在内的大多数人,当编写小型脚本时,习惯使用print来debug,肥肠方便,这没问题,但随着代码不断完善,日志功能一定是不可或缺的,极大程度方便问题溯源以及甩锅,也是每个工程师必备技能。Python自带的logging我个人不推介使

包括我在内的大多数人,当编写小型脚本时,习惯使用print来debug,肥肠方便,这没问题,但随着代码不断完善,日志功能一定是不可或缺的,极大程度方便问题溯源以及甩锅,也是每个工程师必备技能。OnS28资讯网——每日最新资讯28at.com

Python自带的logging我个人不推介使用,不太Pythonic,而开源的Loguru库成为众多工程师及项目中首选,本期将同时对logging及Loguru进行使用对比,希望有所帮助。OnS28资讯网——每日最新资讯28at.com

OnS28资讯网——每日最新资讯28at.com

快速示例

在logging中,默认的日志功能输出的信息较为有限:OnS28资讯网——每日最新资讯28at.com

import logginglogger = logging.getLogger(__name__)def main():    logger.debug("This is a debug message")    logger.info("This is an info message")    logger.warning("This is a warning message")    logger.error("This is an error message")if __name__ == "__main__":    main()

输出(logging默认日志等级为warning,故此处未输出info与debug等级的信息):OnS28资讯网——每日最新资讯28at.com

WARNING:root:This is a warning messageERROR:root:This is an error message

再来看看loguru,默认生成的信息就较为丰富了:OnS28资讯网——每日最新资讯28at.com

from loguru import loggerdef main():    logger.debug("This is a debug message")    logger.info("This is an info message")    logger.warning("This is a warning message")    logger.error("This is an error message")if __name__ == "__main__":    main()

OnS28资讯网——每日最新资讯28at.com

提供了执行时间、等级、在哪个函数调用、具体哪一行等信息。OnS28资讯网——每日最新资讯28at.com

格式化日志

格式化日志允许我们向日志添加有用的信息,例如时间戳、日志级别、模块名称、函数名称和行号。OnS28资讯网——每日最新资讯28at.com

在logging中使用%达到格式化目的:OnS28资讯网——每日最新资讯28at.com

import logging# Create a logger and set the logging levellogging.basicConfig(    level=logging.INFO,    format="%(asctime)s | %(levelname)s | %(module)s:%(funcName)s:%(lineno)d - %(message)s",    datefmt="%Y-%m-%d %H:%M:%S",)logger = logging.getLogger(__name__)def main():    logger.debug("This is a debug message")    logger.info("This is an info message")    logger.warning("This is a warning message")    logger.error("This is an error message")

输出:OnS28资讯网——每日最新资讯28at.com

2023-10-18 15:47:30 | INFO | tmp:<module>:186 - This is an info message2023-10-18 15:47:30 | WARNING | tmp:<module>:187 - This is a warning message2023-10-18 15:47:30 | ERROR | tmp:<module>:188 - This is an error message

而loguru使用和f-string相同的{}格式,更方便:OnS28资讯网——每日最新资讯28at.com

from loguru import loggerlogger.add(    sys.stdout,    level="INFO",    format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {module}:{function}:{line} - {message}",)

日志保存

在logging中,实现日志保存与日志打印需要两个额外的类,FileHandler 和 StreamHandler:OnS28资讯网——每日最新资讯28at.com

import logginglogging.basicConfig(    level=logging.DEBUG,    format="%(asctime)s | %(levelname)s | %(module)s:%(funcName)s:%(lineno)d - %(message)s",    datefmt="%Y-%m-%d %H:%M:%S",    handlers=[        logging.FileHandler(filename="/your/save/path/info.log", level=logging.INFO),        logging.StreamHandler(level=logging.DEBUG),    ],)logger = logging.getLogger(__name__)def main():    logging.debug("This is a debug message")    logging.info("This is an info message")    logging.warning("This is a warning message")    logging.error("This is an error message")if __name__ == "__main__":    main()

但是在loguru中,只需要使用add方法即可达到目的:OnS28资讯网——每日最新资讯28at.com

from loguru import loggerlogger.add(    'info.log',    format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {module}:{function}:{line} - {message}",    level="INFO",)def main():    logger.debug("This is a debug message")    logger.info("This is an info message")    logger.warning("This is a warning message")    logger.error("This is an error message")if __name__ == "__main__":    main()

日志轮换

日志轮换指通过定期创建新的日志文件并归档或删除旧的日志来防止日志变得过大。OnS28资讯网——每日最新资讯28at.com

在logging中,需要一个名为 TimedRotatingFileHandler 的附加类,以下代码示例代表每周切换到一个新的日志文件 ( when=“WO”, interval=1 ),并保留最多 4 周的日志文件 ( backupCount=4 ):OnS28资讯网——每日最新资讯28at.com

import loggingfrom logging.handlers import TimedRotatingFileHandlerlogger = logging.getLogger(__name__)logger.setLevel(logging.DEBUG)# Create a formatter with the desired log formatformatter = logging.Formatter(    "%(asctime)s | %(levelname)-8s | %(module)s:%(funcName)s:%(lineno)d - %(message)s",    datefmt="%Y-%m-%d %H:%M:%S",)file_handler = TimedRotatingFileHandler(    filename="debug2.log", when="WO", interval=1, backupCount=4)file_handler.setLevel(logging.INFO)file_handler.setFormatter(formatter)logger.addHandler(file_handler)def main():    logger.debug("This is a debug message")    logger.info("This is an info message")    logger.warning("This is a warning message")    logger.error("This is an error message")if __name__ == "__main__":    main()

在loguru中,可以通过将 rotation 和 retention 参数添加到 add 方法来达到目的,如下示例,同样肥肠方便:OnS28资讯网——每日最新资讯28at.com

from loguru import loggerlogger.add("debug.log", level="INFO", rotation="1 week", retention="4 weeks")def main():    logger.debug("This is a debug message")    logger.info("This is an info message")    logger.warning("This is a warning message")    logger.error("This is an error message")if __name__ == "__main__":    main()

日志筛选

日志筛选指根据特定条件有选择的控制应输出与保存哪些日志信息。OnS28资讯网——每日最新资讯28at.com

在logging中,实现该功能需要创建自定义日志过滤器类:OnS28资讯网——每日最新资讯28at.com

import logginglogging.basicConfig(    filename="test.log",    format="%(asctime)s | %(levelname)-8s | %(module)s:%(funcName)s:%(lineno)d - %(message)s",    level=logging.INFO,)class CustomFilter(logging.Filter):    def filter(self, record):        return "Cai Xukong" in record.msg# Create a custom logging filtercustom_filter = CustomFilter()# Get the root logger and add the custom filter to itlogger = logging.getLogger()logger.addFilter(custom_filter)def main():    logger.info("Hello Cai Xukong")    logger.info("Bye Cai Xukong")if __name__ == "__main__":    main()

在loguru中,可以简单地使用lambda函数来过滤日志:OnS28资讯网——每日最新资讯28at.com

from loguru import loggerlogger.add("test.log", filter=lambda x: "Cai Xukong" in x["message"], level="INFO")def main():    logger.info("Hello Cai Xukong")    logger.info("Bye Cai Xukong")if __name__ == "__main__":    main()

捕获异常

在logging中捕获异常较为不便且难以调试,如:OnS28资讯网——每日最新资讯28at.com

import logginglogging.basicConfig(    level=logging.DEBUG,    format="%(asctime)s | %(levelname)s | %(module)s:%(funcName)s:%(lineno)d - %(message)s",    datefmt="%Y-%m-%d %H:%M:%S",)def division(a, b):    return a / bdef nested(c):    try:        division(1, c)    except ZeroDivisionError:        logging.exception("ZeroDivisionError")if __name__ == "__main__":    nested(0)
Traceback (most recent call last):  File "logging_example.py", line 16, in nested    division(1, c)  File "logging_example.py", line 11, in division    return a / bZeroDivisionError: division by zero

上面输出的信息未提供触发异常的c值信息,而在loguru中,通过显示包含变量值的完整堆栈跟踪来方便用户识别:OnS28资讯网——每日最新资讯28at.com

Traceback (most recent call last):  File "logging_example.py", line 16, in nested    division(1, c)  File "logging_example.py", line 11, in division    return a / bZeroDivisionError: division by zero

OnS28资讯网——每日最新资讯28at.com

值得一提的是,loguru中的catch装饰器允许用户捕获函数内任何错误,且还会标识发生错误的线程:OnS28资讯网——每日最新资讯28at.com

from loguru import loggerdef division(a, b):    return a / b@logger.catchdef nested(c):    division(1, c)if __name__ == "__main__":    nested(0)

OnS28资讯网——每日最新资讯28at.com

OK,作为普通玩家以上功能足以满足日常日志需求,通过对比logging与loguru应该让大家有了直观感受,哦对了,loguru如何安装?OnS28资讯网——每日最新资讯28at.com

pip install loguru

以上就是本期的全部内容,期待点赞在看,我是啥都生,下次再见。OnS28资讯网——每日最新资讯28at.com

本文链接:http://www.28at.com/showinfo-26-17257-0.html为什么不推荐使用Python原生日志库?

声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。邮件:2376512515@qq.com

上一篇: 如何将Docker的构建时间减少40%

下一篇: Gorm 中的迁移指南

标签:
  • 热门焦点
  • 三分钟白话RocketMQ系列—— 如何发送消息

    我们知道RocketMQ主要分为消息 生产、存储(消息堆积)、消费 三大块领域。那接下来,我们白话一下,RocketMQ是如何发送消息的,揭秘消息生产全过程。注意,如果白话中不小心提到相关代
  • 破圈是B站头上的紧箍咒

    来源 | 光子星球撰文 | 吴坤谚编辑 | 吴先之每年的暑期档都少不了瞄准追剧女孩们的古偶剧集,2021年有优酷的《山河令》,2022年有爱奇艺的《苍兰诀》,今年却轮到小破站抓住了追
  • 共享单车的故事讲到哪了?

    来源丨海克财经与共享充电宝相差不多,共享单车已很久没有被国内热点新闻关照到了。除了一再涨价和用户直呼用不起了。近日多家媒体再发报道称,成都、天津、郑州等地多个共享单
  • 花7万退货退款无门:谁在纵容淘宝珠宝商家造假?

    来源:极点商业作者:杨铭在淘宝购买珠宝玉石后,因为保证金不够赔付,店铺关闭,退货退款难、维权无门的比比皆是。&ldquo;提供相关产品鉴定证书,支持全国复检,可以30天无理由退换货。&
  • 一条抖音4亿人围观 ! 这家MCN比无忧传媒还野

    作者:Hiu 来源:互联网品牌官01 擦边少女空降热搜,幕后推手曝光被网友誉为&ldquo;纯欲天花板&rdquo;的女网红井川里予,近期因为一组哥特风照片登上热搜,引发了一场互联网世界关于
  • 大厂卷向扁平化

    来源:新熵作者丨南枝 编辑丨月见大厂职级不香了。俗话说,兵无常势,水无常形,互联网企业调整职级体系并不稀奇。7月13日,淘宝天猫集团启动了近年来最大的人力制度改革,目前已形成一
  • 信通院:小米、华为等11家应用商店基本完成APP签名及验签工作

    中国信通院表示,目前,小米、华为、OPPO、vivo、360手机助手、百度手机助手、应用宝、豌豆荚和努比亚等9家应用商店,以及抖音和快手2家新型应用分发平
  • 三星Galaxy Z Fold/Flip 5国行售价曝光 :最低7499元/12999元起

    据官方此前宣布,三星将于7月26日也就是明天在韩国首尔举办Unpacked活动,届时将带来带来包括Galaxy Buds 3、Galaxy Watch 6、Galaxy Tab S9、Galaxy
  • 三星Galaxy Z Fold5官方渲染图曝光:13.4mm折叠厚度依旧感人

    据官方此前宣布,三星将于7月26日在韩国首尔举办Unpacked活动,届时将带来带来包括Galaxy Buds 3、Galaxy Watch 6、Galaxy Tab S9、Galaxy Z Flip 5、
Top