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

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

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

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

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

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

快速示例

在logging中,默认的日志功能输出的信息较为有限:iou28资讯网——每日最新资讯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等级的信息):iou28资讯网——每日最新资讯28at.com

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

再来看看loguru,默认生成的信息就较为丰富了:iou28资讯网——每日最新资讯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()

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

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

格式化日志

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

在logging中使用%达到格式化目的:iou28资讯网——每日最新资讯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")

输出:iou28资讯网——每日最新资讯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相同的{}格式,更方便:iou28资讯网——每日最新资讯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:iou28资讯网——每日最新资讯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方法即可达到目的:iou28资讯网——每日最新资讯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()

日志轮换

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

在logging中,需要一个名为 TimedRotatingFileHandler 的附加类,以下代码示例代表每周切换到一个新的日志文件 ( when=“WO”, interval=1 ),并保留最多 4 周的日志文件 ( backupCount=4 ):iou28资讯网——每日最新资讯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 方法来达到目的,如下示例,同样肥肠方便:iou28资讯网——每日最新资讯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()

日志筛选

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

在logging中,实现该功能需要创建自定义日志过滤器类:iou28资讯网——每日最新资讯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函数来过滤日志:iou28资讯网——每日最新资讯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中捕获异常较为不便且难以调试,如:iou28资讯网——每日最新资讯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中,通过显示包含变量值的完整堆栈跟踪来方便用户识别:iou28资讯网——每日最新资讯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

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

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

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

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

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

pip install loguru

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

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

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

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

下一篇: Gorm 中的迁移指南

标签:
  • 热门焦点
  • 红魔电竞平板评测:大屏幕硬实力

    前言:三年的疫情因为要上网课的原因激活了平板市场,如今网课的时代已经过去,大家的生活都恢复到了正轨,这也就意味着,真正考验平板电脑生存的环境来了。也就是面对着这种残酷的
  • 如何正确使用:Has和:Nth-Last-Child

    我们可以用CSS检查,以了解一组元素的数量是否小于或等于一个数字。例如,一个拥有三个或更多子项的grid。你可能会想,为什么需要这样做呢?在某些情况下,一个组件或一个布局可能会
  • 之家push系统迭代之路

    前言在这个信息爆炸的互联网时代,能够及时准确获取信息是当今社会要解决的关键问题之一。随着之家用户体量和内容规模的不断增大,传统的靠"主动拉"获取信息的方式已不能满足用
  • Temu起诉SHEIN,跨境电商战事升级

    来源 | 伯虎财经(bohuFN)作者 | 陈平安日前据外媒报道,拼多多旗下跨境电商平台Temu正对竞争对手SHEIN提起新诉讼,诉状称Shein&ldquo;利用市场支配力量强迫服装厂商与之签订独家
  • iQOO Neo8 Pro真机谍照曝光:天玑9200+和V1+旗舰双芯加持

    去年10月,iQOO推出了iQOO Neo7系列机型,不仅搭载了天玑9000+,而且是同价位唯一一款天玑9000+直屏旗舰,一经上市便受到了用户的广泛关注。在时隔半年后,
  • 回归OPPO两年,一加赢了销量,输了品牌

    成为OPPO旗下主打性能的先锋品牌后,一加屡创佳绩。今年618期间,一加手机全渠道销量同比增长362%,凭借一加 11、一加 Ace 2、一加 Ace 2V三款爆品,一加
  • OPPO K11搭载长寿版100W超级闪充:26分钟充满100%

    据此前官方宣布,OPPO将于7月25日也就是今天下午14:30举办新品发布会,届时全新的OPPO K11将正式与大家见面,将主打旗舰影像,和同档位竞品相比,其最大的卖
  • 联想YOGA 16s 2022笔记本将要推出,屏幕支持触控功能

    联想此前宣布,将于11月2日19:30召开联想秋季轻薄新品发布会,推出联想 YOGA 16s 2022 笔记本等新品。官方称,YOGA 16s 2022 笔记本将搭载 16 英寸屏幕,并且是一
  • Windows 11发布,微软一改往常对老机型开放的态度

    距离 Windows 11 发布已经过去一周,在过去一周里,很多数码爱好者围绕其对 Android 应用的支持、对老机型的升级问题展开了激烈讨论。与以往不同的是,在这次大
Top