添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

使用logging第三方模块

1.RotatingFileHandler(按照文件大小分割)

hdlr = logging.handlers.RotatingFileHandler(LOG_FILE,maxBytes=1024*1024,backupCount=40)

2.TimedRotatingFileHandler(按照时间间隔分割)

hdlr = logging.handlers.TimedRotatingFileHandler(LOG_FILE,when='M',interval=1,backupCount=40)

参数解释:

interval   是指等待多少个单位when的时间后,Logger会自动重建文件,当然,这个文件的创建取决于filename+suffix,若这个文件跟之前的文件有重名,则会自动覆盖掉以前的文件,所以有些情况suffix要定义的不能因为when而重复.

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

when:是一个字符串,用于描述滚动周期的基本单位,字符串的值及意义如下
“S”: Seconds
“M”: Minutes
“H”: Hours
“D”: Days
“W”: Week day (0=Monday)
“midnight”: Roll over at midnight

interval: 滚动周期,单位有when指定,比如:when=’D’,interval=1,表示每天产生一个日志文件

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
from logging.handlers import TimedRotatingFileHandler
class loggerConfig:
    def __init__(self,logname,logpath,level=logging.INFO,formatter="%(asctime)s - %(name)s - %(levelname)s - %(message)s"):
        self.logname=logname
        self.logpath=logpath
        self.level=level
        self.formatter=formatter
    def create_logger(self):
        logger = logging.getLogger(self.logname)
        logger.setLevel(level=self.level)
        # handler = logging.FileHandler(self.logpath)
        #第三方模块的调用调试入口
        #f7 单步进入  进入下一级被调用的函数或者类等
        #f8 单步执行  直接跳转到当前指令行的下一行 不进入被调用的下级函数或者类
        handler = TimedRotatingFileHandler(filename=self.logpath, when="M", interval=1, backupCount=5)
        handler.setLevel(self.level)
        formatter = logging.Formatter(self.formatter)
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        return logger
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from common import esConfig
from common import timetools
from common.loggerConfig import loggerConfig
import datetime
import os
import time
es = esConfig.es
logpath=os.path.abspath('../logs/log.txt')
log=loggerConfig("messageSend",logpath)
logger=log.create_logger()
today=datetime.date.today()
indexname="message-send-"+str(today)
count = 0
while count<15:
    #每次调用logger对象向文件写入文本内容的时候都会自动触发日志轮转和删除检测操作函数
    logger.error("这里是日志内容 %d" %(count))
    time.sleep(5)
    count = count + 1
业务写日志模块

调试日志模块

python实现日志文件的顺序读取和倒序读取

1.python默认是按顺序读取的  但是有些情况需要读取带指定内容并且是最后出现的

2.在python如果需要对日志内容进行分析处理的可以通过调用shell程序来处理

#默认是按顺序读取文件内容
for line in open("../data/message_send.db",encoding="utf-8"):
    if line.startswith("success"):
        print(line.split("_"))
#要取最新的内容必须按照倒序读取
#日志内容通过shell命令操作最合适(倒序 过滤关键字)
#python本身不太适合做文本内容操作
res = os.popen("tac ../data/message_send.db | grep 'success' | head -n 1")
for re in res.readlines():
    print re
View Code # python本身不太适合做文本内容操作 filename= " message_send.db " res = os.popen( " tac %s | grep 'success'| head -n 1 " % (filename)) con = "" for re in res.readlines(): con = re cons =con.split( " _ " ) print (cons[1]) 截取日志中最新成功的时间
fail_2019-11-15 09:51:19,579_此次统计发生异常'total33',还剩9次重试
sueeccess_2019-11-15 11:51:02,523_成功统计0条记录
fail_2019-11-15 10:51:19,579_此次统计发生异常'total33',还剩9次重试
fail_2019-11-15 11:51:19,579_此次统计发生异常'total33',还剩9次重试
fail_2019-11-15 12:51:19,579_此次统计发生异常'total33',还剩9次重试
fail_2019-11-15 09:51:19,579_此次统计发生异常'total33',还剩9次重试
succaaess_2019-11-15 13:51:02,523_成功统计0条记录
success_2019-11-15 14:51:02,523_成功统计0条记录