Python模块丨logging.handlers - 日志处理

Python模块丨logging.handlers - 日志处理

  • TimedRotatingFileHandler

    1
    class logging.handlers.TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None)
  • filename:输出日志文件名的前缀;

  • when

    • ‘S’:秒;
    • ‘M’:分;
    • ‘H’:时;
    • ‘D’:天;
    • ‘W0’-‘W6’:
      • ‘W0’:星期一;
      • ‘W1’:星期二;
      • … … 以此类推
    • ‘midnight’:如果未指定atTime,则在午夜翻转,否则在atTime时翻转
  • interval:是指等待多少个单位when的时间后,Logger会自动重建文件,当然,这个文件的创建取决filename+suffix,若这个文件跟之前的文件有重名,则会自动覆盖掉以前的文件,所以有些情况suffix要定义的不能因为when而重复;

  • backupCount:是保留日志个数。默认的0是不会自动删除掉日志。若设10,则在文件的创建过程中库会判断是否有超过这个10,若超过,则会从最先创建的开始删除。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import logging
import logging.handlers

# logging初始化工作
logging.basicConfig()

# nor的初始化工作
nor = logging.getLogger("nor")
nor.setLevel(logging.INFO)

# 添加TimedRotatingFileHandler到nor
# 定义一个1分钟换一次log文件的handler
filehandler = logging.handlers.TimedRotatingFileHandler("logging_test2", 'M', 1, 0)

# 设置后缀名称,跟strftime的格式一样
filehandler.suffix = "%Y%m%d-%H%M.log"
nor.addHandler(filehandler)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import logging

from logging.handlers import TimedRotatingFileHandler

root = logging.getLogger()
if len(root.handlers) == 0: # 避免重复
level = logging.INFO
filename = os.path.join(HERE,'static/log/log.log').replace('\\','/')
#filename = 'D:\\workspace_myeclipse\\djangopro_dwz\\log.log'
format = '%(asctime)s %(levelname)s %(module)s.%(funcName)s Line:%(lineno)d%(message)s'
hdlr = TimedRotatingFileHandler(filename,"M",1,10)
fmt = logging.Formatter(format)
hdlr.setFormatter(fmt)
root.addHandler(hdlr)