
习惯了使用Python自带的
logging模块记录日志,但是总觉得不够优雅。 Loguru解决了这个问题。guru是印度语中大师的意思,直译就是“日志大师”。


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")@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)参考: https://github.com/Delgan/loguru https://loguru.readthedocs.io/en/stable/overview.html