習慣了使用Python自帶的
logging
模塊記錄日志,但是總覺得不夠優雅。
Loguru解決了這個問題。guru是印度語中大師的意思,直譯就是“日志大師”。
使用pip安裝
pip install loguru
開箱即用
不同的日志等級,輸出效果也不一樣(等級由低到高是DEBUG
、INFO
、WARNING
、ERROR
、CRITICAL
)
logger.debug("That's it, beautiful and simple logging!")
logger.info("That's it, beautiful and simple logging!")
logger.warning("That's it, beautiful and simple logging!")
logger.error("That's it, beautiful and simple logging!")
logger.critical("That's it, beautiful and simple logging!")
統一的add()
函數
add()
函數用于注冊“沉量”sink
,用于管理日志消息。
logger.add(sink='log.txt', format="{time} {level} {message}", filter="my_module", level="INFO")
將上面兩個功能合起來,就能實現最基本的日志功能了。
from loguru import logger
logger.add(sink='log.log', format="{time} - {level} - {message}", level="INFO")
logger.info("That's it, beautiful and simple logging!")
可以用rotation
、retention
、compression
進行日志窗口、更新、壓縮管理。
logger.add("file_1.log", rotation="500 MB") # 日志文件的窗口大小是500M
logger.add("file_2.log", rotation="12:00") # 每天中午12點創建新日志文件
logger.add("file_3.log", rotation="1 week") # 自動更新舊文件
logger.add("file_X.log", retention="10 days") # 清理舊文件
logger.add("file_Y.log", compression="zip") # 壓縮文件
loguru支持f-string
:
logger.info("If you're using Python {}, prefer {feature} of course!", 3.6, feature="f-strings")
Loguru支持在主進程和線程中捕獲異常,使用@logger.catch
from loguru import logger
logger.add(sink='log.log', format="{time} - {level} - {message}", level="INFO")
@logger.catch
def my_function(x, y, z):
return 1 / (x + y + z)
res = my_function(0,0,0)
print(res)
修改日志文字的顏色
logger.add(sys.stdout, colorize=True, format="<green>{time}</green> <level>{message}</level>")
使用enqueue
,可以保證多線程安全、多進程安全
logger.add("somefile.log", enqueue=True)
詳細的異常回溯
使用backtrace
、diagnose
from loguru import logger
logger.add("output.log", backtrace=True, diagnose=True) # 設置為'False'可以保證生產中不泄露信息
def func(a, b):
return a / b
def nested(c):
try:
func(5, c)
except ZeroDivisionError:
logger.exception("What?!")
nested(0)
修改時間格式
logger.add("file.log", format="{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}")
參考:
https://github.com/Delgan/loguru
https://loguru.readthedocs.io/en/stable/overview.html