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

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

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

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

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

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

快速示例

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

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

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

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

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

格式化日志

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

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

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

日志轮换

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

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

日志筛选

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

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

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

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

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

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

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

pip install loguru

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

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

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

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

下一篇: Gorm 中的迁移指南

标签:
  • 热门焦点
  • 十个简单但很有用的Python装饰器

    装饰器(Decorators)是Python中一种强大而灵活的功能,用于修改或增强函数或类的行为。装饰器本质上是一个函数,它接受另一个函数或类作为参数,并返回一个新的函数或类。它们通常用
  • 三言两语说透柯里化和反柯里化

    JavaScript中的柯里化(Currying)和反柯里化(Uncurrying)是两种很有用的技术,可以帮助我们写出更加优雅、泛用的函数。本文将首先介绍柯里化和反柯里化的概念、实现原理和应用
  • Python异步IO编程的进程/线程通信实现

    这篇文章再讲3种方式,同时讲4中进程间通信的方式一、 Python 中线程间通信的实现方式共享变量共享变量是多个线程可以共同访问的变量。在Python中,可以使用threading模块中的L
  • 新电商三兄弟,“抖快红”成团!

    来源:价值研究所作 者:Hernanderz 随着内容电商的概念兴起,抖音、快手、小红书组成的&ldquo;新电商三兄弟&rdquo;成为业内一股不可忽视的势力,给阿里、京东、拼多多带去了巨大压
  • 华为和江淮汽车合作开发百万元问界MPV?双方回应来了

    8月1日消息,郭明錤今天在社交平台发文称,华为正在和江淮汽车合作,开发售价在100万元的问界MPV,预计在2024年第2季度量产,销量目标为上市首年交付5万辆。
  • 华为Mate60标准版细节曝光:经典星环相机模组回归

    这段时间以来,关于华为新旗舰的爆料日渐密集。据此前多方爆料,今年华为将开始恢复一年双旗舰战略,除上半年推出的P60系列外,往年下半年的Mate系列也将
  • iQOO 11S评测:行业唯一的200W标准版旗舰

    【Techweb评测】去年底,iQOO推出了“电竞旗舰”iQOO 11系列,作为一款性能强机,该机不仅全球首发2K 144Hz E6全感屏,搭载了第二代骁龙8平台及144Hz电竞
  • 华为举行春季智慧办公新品发布会 首次推出电子墨水屏平板

    北京时间2月27日晚,华为在巴塞罗那举行春季智慧办公新品发布会,在海外市场推出之前已经在中国市场上市的笔记本、平板、激光打印机等办公产品,并首次推出搭载
  • 利用职权私自解除被封帐号 Meta开除20多名员工

    11月18日消息,据外媒援引知情人士表示,过去一年时间内,Facebook母公司Meta解雇或处罚了20多名员工以及合同工,指控这些人通过内部系统以不当方式重置用户帐号,其
Top