Python—logging日志模块基本用法
日志一共分成5个等级,从低到高分别是:
DEBUG、INFO、WARNING、ERROR、CRITICAL
默认的是 WARNING,当在WARNING或之上时才被跟踪
控制台输出
import logging
# 通过logging.basicConfig函数对日志的输出格式及方式做相关配置
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(filename)s[line:%(lineno)d] - %(name)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S", # 日期格式
level=logging.INFO # 最低显示等级
)
logging.info('this is a loggging info message')
logging.debug('this is a loggging debug message')
logging.warning('this is loggging a warning message')
logging.error('this is an loggging error message')
logging.critical('this is a loggging critical message')
输出至文件
import logging
logging.basicConfig(
filename="./log.txt",
filemode="a+",
format="%(asctime)s - %(levelname)s - %(filename)s[line:%(lineno)d] - %(name)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
level=logging.INFO
)
logging.info('this is a loggging info message')
logging.debug('this is a loggging debug message')
logging.warning('this is loggging a warning message')
logging.error('this is an loggging error message')
logging.critical('this is a loggging critical message')
既要把日志输出到控制台,也要写入日志文件
import logging
# create a logger
logger = logging.getLogger()
logger.setLevel(logging.INFO) # Log等级开关
# create a handler for write to log file
logfile = './log.txt'
fh = logging.FileHandler(logfile, mode='a+')
fh.setLevel(logging.DEBUG) # 输出到file的log等级开关
# create a handler for output to console
ch = logging.StreamHandler()
ch.setLevel(logging.WARNING) # 输出到console的log等级开关
# define the format of handler's output
formatter = logging.Formatter(fmt="%(asctime)s - %(levelname)s - %(filename)s[line:%(lineno)d] - %(name)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S")
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add logger to handler
logger.addHandler(fh)
logger.addHandler(ch)
# 日志
logger.debug('this is a logger debug message')
logger.info('this is a logger info message')
logger.warning('this is a logger warning message')
logger.error('this is a logger error message')
logger.critical('this is a logger critical message')