风-fmgao

导航

logger常用方法

#!/usr/bin/env python
# encoding: utf-8  
# Date: 2018/5/25


import logging
from logging import handlers
# 日志过滤
class IgnoreBackupLogFilter(logging.Filter):
    '''忽略带db backup的日志'''
    def filter(self, record): # 固定写法
        return 'db backup' in record.getMessage() # True False

# 1.生成logger对象
logger = logging.getLogger('web')
logger.setLevel(logging.DEBUG)

# 1.1 把filter对象添加到logger中
logger.addFilter(IgnoreBackupLogFilter())


# 2.生成handler对象
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
fh = logging.FileHandler('web.log')
# 日志切割 10字节 按照大小截取
# fh = handlers.RotatingFileHandler('web.log', maxBytes=10, backupCount=3)
# 日志切割 时间 按照时间截取
# fh = handlers.TimedRotatingFileHandler('web1.log', when='s', interval=5, backupCount=3)
fh.setLevel(logging.WARNING)

# 2.1 把handler对象绑定到logger
logger.addHandler(ch)
logger.addHandler(fh)

# 3.生成formatter对象

# 3.1 把formatter对象绑定handler对象
file_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(lineno)d - %(message)s')

ch.setFormatter(console_formatter)
fh.setFormatter(file_formatter)

logger.warning('test warning')
logger.warning('test warning db backup')
logger.debug('test log')
logger.info('test log 2')





posted on 2018-05-25 22:41  风-fmgao  阅读(3030)  评论(0编辑  收藏  举报