import logging
from logging.handlers import TimedRotatingFileHandler

log_file_name = "./hello.log"  # log输出文件名称
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')  # 定义日志输出格式(formatter)
logger = logging.getLogger('mylogger')  # 创建一个logger
logger.setLevel(logging.INFO)  # 设置logger级别
BACKUP_FILES_COUNT = 3
# 日志切割,TimedRotatingFileHandler
# # 创建一个TimedRotatingFileHandler,用于日志切割
handler = TimedRotatingFileHandler(filename=log_file_name, when='M', interval=1, backupCount=BACKUP_FILES_COUNT)
"""
# Calculate the real rollover interval, which is just the number of
# seconds between rollovers.  Also set the filename suffix used when
# a rollover occurs.  Current 'when' events supported:
# S - Seconds
# M - Minutes
# H - Hours
# D - Days
# midnight - roll over at midnight
# W{0-6} - roll over on a certain day; 0 - Monday
#
# Case of the 'when' specifier is not important; lower or upper case
# will work.
"""
handler.setFormatter(formatter)  # 给handler添加formatter
handler.suffix = '%Y-%m-%d_%H-%M' # 切割后的日志设置后缀
"""
# handler.suffix = '%Y-%m-%d_%H-%M' # 切割后的日志设置后缀
# 注意suffix需要和源码TimedRotatingFileHandler中self.suffix保持格式一直,不然可能会导致日志无法自动删除
"""
logger.addHandler(handler)  # logger添加上handler

# 输出到控制台,StreamHandler
ch = logging.StreamHandler()  # 创建一个StreamHandler,用于输出到控制台
ch.setLevel(logging.INFO)  # 设置StreamHandler的log级别
ch.setFormatter(formatter)  # 给handler添加formatter
logger.addHandler(ch)  # logger添加handler


logger.debug("msg")
logger.info("msg")
logger.worning("msg")
logger.error("msg")