Look at the piece of code:
import logging
from logging.handlers import TimedRotatingFileHandler
def init_logger(port):
logFilePath = 'logs/test'+str(port)+'.log'
logger = logging.getLogger()
logger.setLevel(logging.INFO) #设置log级别,INFO(包含)以上都会报警
handler = TimedRotatingFileHandler(logFilePath,
when = 'midnight',
interval = 1,
backupCount=0)
#设置记录格式,按照 [当前时间-等级-信息] 记录
formatter = logging.Formatter('[%(asctime)s-%(levelname)s - %(message)s]')
handler.setFormatter(formatter)
logger.addHandler(handler)
return logger
The function code is in the logs / directory by day log, and create a new log file at 00:00 every day. Assuming that the incoming port is 10086, the log naming rules: test10086.log.xxxx-xxxx , where xxxx-xxxx for the year - month - day .
TimedRotatingFileHandler :
- TimedRotatingFileHandler be understood as a logging type may be provided a fixed time interval, which is integrated in the logging in, call directly instantiated and configuration can be used
- TimedRotatingFileHandler constructor is:
TimedRotatingFileHandler( filename , when , interval , backupCount) # filename :输出日志的文件名称前缀,比如说 test.log 这样的就是日志文件名前缀 # when :一个字符串,定义了日志切分的间隔时间单位,这是一个枚举类,可选参数如下: # "S":Second 秒 # "M":Minutes 分钟 # "H":Hour 小时 # "D":Days 天 # "W":Week day(0 = Monday) # "midnight":Roll over at midnight # interval:间隔时间单位的个数,指等待多少个 when 的时间后 Logger 会自动重建日志 # 继续进行记录。如果创建的文件和已有文件存在重名的情况,则会对历史的文件 # 进行覆盖操作。 # backupCount :保留日志的文件个数,默认参数为0,表示保留所有日志。 # 如果设置为 N(正整数),则只保留最多N个最新的日志文件。
Reproduced in: https: //www.jianshu.com/p/e4c68816b5cf