系统:Windows 10 编辑器:JetBrains PyCharm Community Edition 2018.2.2 x64
Part 1:场景描述

Part 2:代码

import os
import logging
def write_log(level, msg):
log_file = os.path.join(os.getcwd(), 'logINFO.txt')
logging.basicConfig(
# 定义输出到文件的log级别,大于此级别的都被输出
level=logging.INFO,
# 定义输出log的格式
format='日志生成时间:%(asctime)s 执行文件名:%(filename)s[line:%(lineno)d] 级别:%(levelname)s 输出信息:%(message)s',
datefmt='%Y-%m-%d %A %H:%M:%S', # 时间
filename=log_file, # log文件名
filemode='a+') # 写入模式“w”或“a”
if level == "debug":
logging.debug(msg)
elif level == "info":
logging.info(msg)
elif level == "warning":
logging.warning(msg)
elif level == "error":
logging.error(msg)
elif level == "critical":
logging.critical(msg)
else:
logging.info(msg)
msg = "log1"
level = "debug"
write_log(level, msg)
msg = "log2"
level = "info"
write_log(level, msg)
msg = "log3"
level = "warning"
write_log(level, msg)
msg = "log4"
level = "error"
write_log(level, msg)
msg = "log5"
level = "critical"
write_log(level, msg)代码截图


Part 3:执行结果

level=logging.INFO,输出 ≥ INFO级别的问题,输出了INFO,WARNING,ERROR,CRITICAL
INFO
level=logging.DEBUG,输出 ≥ DEBUG级别的问题,发现所有的都输出了DEBUG

level=logging.ERROR,输出 ≥ ERROR级别的问题,输出了ERROR,CRITICAL
ERROR

Part 4:部分代码解读

logging.basicConfig,设置输出日志各种参数format='日志生成时间:%(asctime)s 执行文件名:%(filename)s[line:%(lineno)d] 级别:%(levelname)s 输出信息:%(message)s'filemode='a+,在原文件基础上追加%(asctime)s:时间,配合datefmt='%Y-%m-%d %A %H:%M:%S',定义输出时间格式%(filename)s,所在文件[line:%(lineno)d]:代码所在行%(message)s:拟输出信息level=logging.INFO,设置输出最低级别
输出结果
logging.critical等,否则就失去很大一部分意义本文为原创作品,欢迎分享朋友圈