轉載來源:微信公衆號:程序員學長 https://mp.weixin.qq.com/s/csxPONEaUbTdoRMd9opuMw
大家好,我是小寒。
今天給大家分享一個神奇的 python 庫,loguru
https://github.com/Delgan/loguru
Loguru 是一個旨在爲 Python 帶來愉快的日誌記錄的庫,它可以完全增強你的日誌記錄體驗,並且非常易於使用。
初體驗
庫的安裝
安裝 Loguru 也非常簡單,可以直接使用 pip 進行安裝。
pip install loguru
在 Loguru 中,如果需要將調試日誌輸出到終端,可以執行以下操作。
from loguru import logger
logger.debug("That's it, beautiful and simple logging!")
如果需要將日誌輸出到文件中,只需這樣做。
from loguru import logger
logger.add("file_{time}.log")
logger.debug("That's it, beautiful and simple logging!")
這將在當前運行的文件夾中生成 file_current time.log 的日誌文件。
滾動日誌和壓縮
使用 Loguru 你可以輕鬆實現滾動日誌。
按時間滾動
比如要按時間滾動,只需要在 logger.add 參數中添加一個 rotation 參數即可。
from loguru import logger
logger.add("file_2.log", rotation="12:00") # Create new file at 12AM
logger.debug("That's it, beautiful and simple logging!")
這樣,如果當前時間超過了這個設定的時間,就會生成一個新的日誌文件。如果沒有,請使用原始日誌文件。
按大小滾動
除了按時間滾動日誌外,Loguru 還可以按日誌大小滾動。
from loguru import logger
logger.add("file_1.log", rotation="1 MB")
logger.debug("That's it, beautiful and simple logging!")
這樣,一旦日誌文件大小超過1MB,就會生成一個新的日誌文件。
壓縮日誌
如果你不想刪除原來的日誌文件,Loguru 還支持直接壓縮日誌。
from loguru import logger
logger.add("file_Y.log", compression="zip")
其它特性
定製顏色
Loguru 支持自定義顏色,如果你不喜歡它的默認顏色,你可以這樣更改。
logger.add(sys.stdout, colorize=True, format="<green>{time}</green> <level>{message}</level>")
多進程安全
Loguru 默認是線程安全的,但它不是多進程安全的。
但如果你需要多進程/異步日誌記錄,它也支持,只需添加一個 enqueue 參數即可。
logger.add("somefile.log", enqueue=True)
回溯支持
對於日誌來說,沒有錯誤棧的日誌是沒有靈魂的。Loguru 允許你顯示整個堆棧信息以幫助你發現問題(包括變量)。例如:
def func(a, b):
return a / b
def nested(c):
try:
func(5, c)
except ZeroDivisionError:
logger.exception("What?!")
nested(0)
電子郵件提醒
Loguru 可以與強大的電子郵件通知模塊結合使用,以便在程序意外失敗時接收電子郵件,或發送許多其他類型的通知。
import notifiers
params = {
"username": "[email protected]",
"password": "abc123",
"to": "[email protected]"
}
# Initialize email
notifier = notifiers.get_notifier("gmail")
notifier.notify(message="The application is running!", **params)
# Email alert for error
from notifiers.logging import NotificationHandler
handler = NotificationHandler("gmail", defaults=params)
logger.add(handler, level="ERROR")
這樣配置後,每次產生 Error 日誌時,程序都會自動向你的郵箱發送警報,真是方便。除了這些功能之外,Loguru 還支持與 Python 原生 Logging 模塊的兼容,你可以將原始標準記錄器記錄的所有信息轉移到 Loguru 中。你還可以基於 Loguru 自定義新的日誌級別,並自定義你喜歡的結構化數據。