日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當前位置:首頁 > 科技  > 軟件

為什么不推薦使用Python原生日志庫?

來源: 責編: 時間:2023-11-06 17:19:10 250觀看
導讀包括我在內的大多數人,當編寫小型腳本時,習慣使用print來debug,肥腸方便,這沒問題,但隨著代碼不斷完善,日志功能一定是不可或缺的,極大程度方便問題溯源以及甩鍋,也是每個工程師必備技能。Python自帶的logging我個人不推介使

包括我在內的大多數人,當編寫小型腳本時,習慣使用print來debug,肥腸方便,這沒問題,但隨著代碼不斷完善,日志功能一定是不可或缺的,極大程度方便問題溯源以及甩鍋,也是每個工程師必備技能。06M28資訊網——每日最新資訊28at.com

Python自帶的logging我個人不推介使用,不太Pythonic,而開源的Loguru庫成為眾多工程師及項目中首選,本期將同時對logging及Loguru進行使用對比,希望有所幫助。06M28資訊網——每日最新資訊28at.com

06M28資訊網——每日最新資訊28at.com

快速示例

在logging中,默認的日志功能輸出的信息較為有限:06M28資訊網——每日最新資訊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等級的信息):06M28資訊網——每日最新資訊28at.com

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

再來看看loguru,默認生成的信息就較為豐富了:06M28資訊網——每日最新資訊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()

06M28資訊網——每日最新資訊28at.com

提供了執行時間、等級、在哪個函數調用、具體哪一行等信息。06M28資訊網——每日最新資訊28at.com

格式化日志

格式化日志允許我們向日志添加有用的信息,例如時間戳、日志級別、模塊名稱、函數名稱和行號。06M28資訊網——每日最新資訊28at.com

在logging中使用%達到格式化目的:06M28資訊網——每日最新資訊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")

輸出:06M28資訊網——每日最新資訊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相同的{}格式,更方便:06M28資訊網——每日最新資訊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:06M28資訊網——每日最新資訊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方法即可達到目的:06M28資訊網——每日最新資訊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()

日志輪換

日志輪換指通過定期創建新的日志文件并歸檔或刪除舊的日志來防止日志變得過大。06M28資訊網——每日最新資訊28at.com

在logging中,需要一個名為 TimedRotatingFileHandler 的附加類,以下代碼示例代表每周切換到一個新的日志文件 ( when=“WO”, interval=1 ),并保留最多 4 周的日志文件 ( backupCount=4 ):06M28資訊網——每日最新資訊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 方法來達到目的,如下示例,同樣肥腸方便:06M28資訊網——每日最新資訊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()

日志篩選

日志篩選指根據特定條件有選擇的控制應輸出與保存哪些日志信息。06M28資訊網——每日最新資訊28at.com

在logging中,實現該功能需要創建自定義日志過濾器類:06M28資訊網——每日最新資訊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函數來過濾日志:06M28資訊網——每日最新資訊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中捕獲異常較為不便且難以調試,如:06M28資訊網——每日最新資訊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中,通過顯示包含變量值的完整堆棧跟蹤來方便用戶識別:06M28資訊網——每日最新資訊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

06M28資訊網——每日最新資訊28at.com

值得一提的是,loguru中的catch裝飾器允許用戶捕獲函數內任何錯誤,且還會標識發生錯誤的線程:06M28資訊網——每日最新資訊28at.com

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

06M28資訊網——每日最新資訊28at.com

OK,作為普通玩家以上功能足以滿足日常日志需求,通過對比logging與loguru應該讓大家有了直觀感受,哦對了,loguru如何安裝?06M28資訊網——每日最新資訊28at.com

pip install loguru

以上就是本期的全部內容,期待點贊在看,我是啥都生,下次再見。06M28資訊網——每日最新資訊28at.com

本文鏈接:http://www.www897cc.com/showinfo-26-17257-0.html為什么不推薦使用Python原生日志庫?

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 如何將Docker的構建時間減少40%

下一篇: Gorm 中的遷移指南

標簽:
  • 熱門焦點
  • MIX Fold3包裝盒泄露 新機本月登場

    小米的全新折疊屏旗艦MIX Fold3將于本月發布,近日該機的真機包裝盒在網上泄露。從圖上來看,新的MIX Fold3包裝盒在外觀設計方面延續了之前的方案,變化不大,這也是目前小米旗艦
  • 從 Pulsar Client 的原理到它的監控面板

    背景前段時間業務團隊偶爾會碰到一些 Pulsar 使用的問題,比如消息阻塞不消費了、生產者消息發送緩慢等各種問題。雖然我們有個監控頁面可以根據 topic 維度查看他的發送狀態,
  • 每天一道面試題-CPU偽共享

    前言:了不起:又到了每天一到面試題的時候了!學弟,最近學習的怎么樣啊 了不起學弟:最近學習的還不錯,每天都在學習,每天都在進步! 了不起:那你最近學習的什么呢? 了不起學弟:最近在學習C
  • 電視息屏休眠仍有網絡上傳 愛奇藝被質疑“薅消費者羊毛”

    記者丨寧曉敏 見習生丨汗青出品丨鰲頭財經(theSankei) 前不久,愛奇藝發布了一份亮眼的一季報,不僅營收和會員營收創造歷史最佳表現,其運營利潤也連續6個月實現增長。自去年年初
  • 中國家電海外掘金正當時|出海專題

    作者|吳南南編輯|胡展嘉運營|陳佳慧出品|零態LT(ID:LingTai_LT)2023年,出海市場戰況空前,中國創業者在海外紛紛摩拳擦掌,以期能夠把中國的商業模式、創業理念、戰略打法輸出海外,他們依
  • 一條抖音4億人圍觀 ! 這家MCN比無憂傳媒還野

    作者:Hiu 來源:互聯網品牌官01 擦邊少女空降熱搜,幕后推手曝光被網友譽為&ldquo;純欲天花板&rdquo;的女網紅井川里予,近期因為一組哥特風照片登上熱搜,引發了一場互聯網世界關于
  • 年輕人的“職場羞恥感”,無處不在

    作者:馮曉亭 陶 淘 李 欣 張 琳 馬舒葉來源:燃次元&ldquo;人在職場,應該選擇什么樣的著裝?&rdquo;近日,在網絡上,一個與著裝相關的帖子引發關注,在該帖子里,一位在高級寫字樓亞洲金
  • 三星推出Galaxy Tab S9系列平板電腦以及Galaxy Watch6系列智能手表

    2023年7月26日,三星電子正式發布了Galaxy Z Flip5與Galaxy Z Fold5。除此之外,Galaxy Tab S9系列平板電腦以及三星Galaxy Watch6系列智能手表也同期
  • 華為舉行春季智慧辦公新品發布會 首次推出電子墨水屏平板

    北京時間2月27日晚,華為在巴塞羅那舉行春季智慧辦公新品發布會,在海外市場推出之前已經在中國市場上市的筆記本、平板、激光打印機等辦公產品,并首次推出搭載
Top 主站蜘蛛池模板: 安福县| 新郑市| 台州市| 临西县| 赞皇县| 乳山市| 广饶县| 青铜峡市| 桑日县| 正定县| 油尖旺区| 金华市| 甘南县| 芮城县| 黔西| 余庆县| 射阳县| 合作市| 平山县| 贵溪市| 舟曲县| 东兴市| 中西区| 雅安市| 上虞市| 宜宾市| 舟山市| 永丰县| 奉化市| 论坛| 涿鹿县| 女性| 上杭县| 青神县| 永昌县| 眉山市| 福贡县| 合江县| 英吉沙县| 营口市| 新和县|