python logging模块,包括控制台输出以及存入日志文件的一个方法。
import logging
from logging import handlers
def logging_set(
filename="default",
level=logging.INFO,
datefmt="%Y-%m-%d %H:%M:%S",
formatter='%(asctime)s [%(module)s] %(levelname)s [%(message)s]'):
logger = logging.getLogger(filename)
format_str = logging.Formatter(formatter, datefmt)
logger.setLevel(level)
# 控制台输出,防止重复写入
if not logger.handlers:
streamhandler = logging.StreamHandler()
streamhandler.setLevel(level)
streamhandler.setFormatter(format_str)
logger.addHandler(streamhandler)
# 存入日志文件
rotatinghandler = handlers.RotatingFileHandler(
filename, mode="a", maxBytes=1024 * 1024 * 100, encoding="utf8")
rotatinghandler.setLevel(level)
rotatinghandler.setFormatter(format_str)
logger.addHandler(rotatinghandler)
return logger
LOGGER = logging_set("./logs/detail.log")
LOGGER.info("success")
输出结果如下: