案例代码
import logging
import datetime
sys_logger = logging.getLogger(__name__) # 创建日志对象
sys_logger.setLevel(logging.DEBUG) # 设置日志的级别
# 创建 logging format
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") # 设置日志输出的格式
# 创建FileHandler输出到磁盘
year = datetime.datetime.now().year
month = datetime.datetime.now().month
log_name = str(year) + "_" + str(month) + "_sys.log" # 拼接日志名字
fhander = logging.FileHandler(log_name, mode='a', encoding="utf-8") # 将每条日志追加到文件中
fhander.setFormatter(formatter)
fhander.setLevel(logging.DEBUG)
# 添加handlers到logger
sys_logger.addHandler(fhander)
# 使用
sys_logger.info("正常")
sys_logger.warning("warning")
sys_logger.error("error")
输出结果
2020-04-27 21:51:24,094 - __main__ - INFO - 正常
2020-04-27 21:51:24,095 - __main__ - WARNING - warning
2020-04-27 21:51:24,095 - __main__ - ERROR - error