📅  最后修改于: 2023-12-03 15:06:19.092000             🧑  作者: Mango
乳胶日志是一个基于Python的日志记录库,能够记录程序的运行状态并提供详细的错误信息。
可以使用pip安装:
pip install loguru
from loguru import logger
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!")
logger.critical("This is a critical message!")
输出:
2022-05-09 16:43:16.284 | DEBUG | __main__:<module>:3 - This is a debug message!
2022-05-09 16:43:16.284 | INFO | __main__:<module>:4 - This is an info message.
2022-05-09 16:43:16.284 | WARNING | __main__:<module>:5 - This is a warning message!
2022-05-09 16:43:16.284 | ERROR | __main__:<module>:6 - This is an error message!
2022-05-09 16:43:16.284 | CRITICAL | __main__:<module>:7 - This is a critical message!
from loguru import logger
logger.add("file.log", format="{time} {level} {message}", level="INFO")
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!")
logger.critical("This is a critical message!")
输出:
2022-05-09 16:43:16.284 | INFO | __main__:<module>:5 - This is an info message.
2022-05-09 16:43:16.284 | WARNING | __main__:<module>:6 - This is a warning message!
2022-05-09 16:43:16.284 | ERROR | __main__:<module>:7 - This is an error message!
2022-05-09 16:43:16.284 | CRITICAL | __main__:<module>:8 - This is a critical message!
同时,日志也被写入到了file.log文件中。
from loguru import logger
logger_a = logger.bind(module="Module A")
logger_b = logger.bind(module="Module B")
logger_a.info("This is a message from Module A!")
logger_b.info("This is a message from Module B!")
输出:
2022-05-09 16:43:16.284 | INFO | __main__:<module>:4 - This is a message from Module A! | Module A
2022-05-09 16:43:16.284 | INFO | __main__:<module>:5 - This is a message from Module B! | Module B
from loguru import logger
logger.add(
"file.log",
format="{time} {level} {module} {message}",
level="INFO"
)
logger_a = logger.bind(module="Module A")
logger_b = logger.bind(module="Module B")
logger_a.info("This is a message from Module A!")
logger_b.info("This is a message from Module B!")
输出和日志文件格式:
2022-05-09 16:43:16.284 | INFO | Module A | This is a message from Module A!
2022-05-09 16:43:16.284 | INFO | Module B | This is a message from Module B!
from loguru import logger
logger.add(
"file_{time}.log",
format="{time} {level} {module} {message}",
level="INFO",
rotation="10 MB",
compression="zip"
)
logger_a = logger.bind(module="Module A")
for i in range(10000):
logger_a.info(f"This is message {i}")
输出:
产生了多个压缩文件:
file_2022-05-09_12-52-20.000000.zip
file_2022-05-09_12-52-25.000000.zip
file_2022-05-09_12-52-35.000000.zip
file_2022-05-09_12-52-46.000000.zip
file_2022-05-09_12-53-01.000000.zip
日志文件轮换的时间间隔和大小等可根据需求设定。
乳胶日志基于MIT协议开源。