LogZero稳健有效的日志工具
LogZero 是一个稳健有效的 Python 2 和 Python 3 日志工具。
特性
可以很方便地打印到终端或者滚动日志
提供完整可配置的Python Logger对象
输出格式漂亮,在终端中根据不同的日志分级显示不同的颜色。
Windows终端中也能区分颜色
能很好地处理编码问题,遇到特殊字符也不会崩溃
多个Logger可以输出到同一个日志文件
支持配置全局Logger和局部Logger
兼容Python2和3
只有一个代码文件
MIT许可证
灵感来源于Tornado框架
示例
from logzero import logger logger.debug("hello") logger.info("info") logger.warn("warn") logger.error("error") # This is how you'd log an exception try: raise Exception("this is a demo exception") except Exception as e: logger.exception(e)
添加日志滚动也很容易
import logzero from logzero import logger # Setup rotating logfile with 3 rotations, each with a maximum filesize of 1MB: logzero.logfile("/tmp/rotating-logfile.log", maxBytes=1e6, backupCount=3) # Log messages logger.info("This log message goes to the console and the logfile")
下面是一些例子说明如何使用日志文件、自定义格式以及设置最低日志等级。
import logging import logzero from logzero import logger # This log message goes to the console logger.debug("hello") # Set a minimum log level logzero.loglevel(logging.INFO) # Set a logfile (all future log messages are also saved there) logzero.logfile("/tmp/logfile.log") # You can also set a different loglevel for the file handler logzero.logfile("/tmp/logfile.log", loglevel=logging.ERROR) # Set a rotating logfile (replaces the previous logfile handler) logzero.logfile("/tmp/rotating-logfile.log", maxBytes=1000000, backupCount=3) # Disable logging to a file logzero.logfile(None) # Set a custom formatter formatter = logging.Formatter('%(name)s - %(asctime)-15s - %(levelname)s: %(message)s'); logzero.formatter(formatter) # Log some variables logger.info("var1: %s, var2: %s", var1, var2
评论