参考:
https://github.com/Delgan/loguru
https://loguru.readthedocs.io/en/stable/overview.html
https://blog.csdn.net/Kangyucheng/article/details/112794185
Loguru是一个高效打印Log的库,试用后你会喜欢上它的。
安装
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函数
将日志输出到了log.txt文件中。
logger.add(sink='log.txt', format="{time} {level} {message}", filter="my_module", level="INFO")
使用参数对保存日志进行操作
logger.add("file_1.log", rotation="500 MB") # Automatically rotate too big file
logger.add("file_2.log", rotation="12:00") # New file is created each day at noon
logger.add("file_X.log", retention="10 days") # Cleanup after some time
logger.add("file_Y.log", compression="zip") # Save some loved space
支持{}变量
logger.info("If you're using Python {}, prefer {feature} of course!", 3.6, feature="f-strings")
修改时间格式
logger.add("file.log", format="{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}")
只保存文件,不在console中输出
logger.remove(handler_id = None) # 清除之前的设置
记录到两个日志文件中
根据filter来进行区分logger的,再用logger.bind()来做logger的区分。
logger.add("gui.log",filter = lambda record:record["extra"]["name"]=="gui_log")
logger.add("serial.log",filter = lambda record:record["extra"]["name"]=="serial_log")
logger_gui = logger.bind(name="gui_log")
logger_serial = logger.bind(name="serial_log")
logger_gui.info("guis")
logger_serial("serial")
按照日志等级记录到不同文件
logger.add("info.log",level = "INFO",filter=lambda x: 'INFO' in str(x['level']).upper()
logger.add("error.log",level = "ERROR",filter=lambda x: 'ERROR' in str(x['level']).upper()