logzero打印日志

Published: 18 Jul 2019 Category: python

logzero是Python的一个日志库,易用性比logging更高一些,不同日志级别可显示不同颜色,很赞。

安装的话很简单,只需要pip install logzero即可。使用的话,先看最简单的,日志输出到控制台

from logzero import logger

# log messages are sent to the console
logger.debug("hello")
logger.info("info")
logger.warning("warning")
logger.error("error")

以上代码运行结果如下图所示

demo_output.png (458×153)

当然还可以设置日志级别,控制日志显示

import logging
import logzero
from logzero import logger

logzero.loglevel(logging.WARNING)  # set log level
logger.debug("hello")  # will not show up
logger.info("info")  # will not show up
logger.warning("warning")
logger.error("error")

日志除打印到控制台外,还可以打到文件中

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)

Refs