python logging日誌玩法舉例

logging

filter & dictConfig

項目中須要改造以前的垃圾日誌輸出和配置形式,研究了一下logging模塊的字典配置和filter過濾器功能。html

demo以下(部分摘自python官網文檔):
talk is cheap, show you code!python

'''
介紹logging config模塊功能,for example
'''
import logging.config
import logging
# 自定義filter功能


class MyFilter(logging.Filter):
    '''
    繼承logging.Filter,並複寫filter方法
    '''

    def __init__(self, param=None, param2=None):
        '''
        param:參數是定義的filter中的param字段
        '''
        self.param = param
        self.param2 = param2

    def filter(self, record):
        def param(x): return x not in record.msg

        if self.param is None:
            allow = True
        else:

            allow = all(param(x) for x in self.param)
            # allow = self.param not in record.msg
        if allow:
            record.msg = 'changed: ' + record.msg  # filter能夠對匹配的規則作一些特殊處理

        # 若是有key關鍵字,則在msg中加上value信息,單純測試,目前沒看到實際應用的場景
        if self.param2 is not None:
            for x in self.param2.keys():
                if not param(x):
                    record.msg = '{}'.format(self.param2[x]) + record.msg

        return allow


# config是一個字典,dictConfig解析字典數據
LOGGING = {
    'version': 1.0,
    'formatters': {
        'f1': {
            'format': '%(levelname)-8s %(asctime)s %(name)-8s %(filename)-15s:%(lineno)-3d %(threadName)-10s %(thread)-15d %(message)s'
        }
    },
    'filters': {
        'myfilter': {
            '()': MyFilter,  # 定義的類
            'param': ['noshow', 'nodisplay'],  # 傳給param的參數列表
            'param2': {'key': 'value'}          # 測試是否支持另外一種形式
        }
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'f1',
            'filters': ['myfilter'],
            'level': 'DEBUG'
        },
        'info': {
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'formatter': 'f1',
            'filename': 'logconfig_info.log',
            'level': 'INFO',
            'when': 'M',
            'backupCount': 180
        },
        'error': {
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'formatter': 'f1',
            'filename': 'logconfig_error.log',
            'level': 'ERROR',
            'when': 'M',
            'backupCount': 180
        }
    },
    'logger': {  # 未使用到之中模式,除非代碼中各個模塊使用了不一樣的日誌輸出格式等纔可能有用吧
        'abc': {
            'handlers': ['console']
        },
        'a.b.c': {
            'handlers': ['info']
        }

    },
    # root是全部定義的logger的父日誌記錄器
    'root': {
        'handlers': ['console', 'info', 'error'],
        'level': 'DEBUG'        # root默認是warning的,因此須要將root level設置爲DEBUG,經過handler中的level進行控制
    }
}
logging.config.dictConfig(LOGGING)
logger3 = logging.getLogger(__name__)

logger1 = logging.getLogger('abc')

while True:
    try:
        import time
        logger3.error('hello world')
        logger3.warning('helloworld')
        logger3.info('hw')
        logger3.info('hw noshow')
        logger3.info('hw nodisplay')
        logger3.debug('GET /')
        logger3.debug('POST / key')

        logger1.debug('logger1...')
        time.sleep(2)
    except KeyboardInterrupt:
        break

'''
日誌輸出:
ERROR    2020-04-30 15:06:09,538 __main__ logging_config.py:104 MainThread 6692            changed: hello world
WARNING  2020-04-30 15:06:09,540 __main__ logging_config.py:105 MainThread 6692            changed: helloworld
INFO     2020-04-30 15:06:09,540 __main__ logging_config.py:106 MainThread 6692            changed: hw
DEBUG    2020-04-30 15:06:09,540 __main__ logging_config.py:109 MainThread 6692            changed: GET /
DEBUG    2020-04-30 15:06:09,540 __main__ logging_config.py:110 MainThread 6692            valuechanged: POST / key
DEBUG    2020-04-30 15:06:09,540 abc      logging_config.py:112 MainThread 6692            changed: logger1...
'''

總結

  • 好好看官方文檔,大有裨益!

https://docs.python.org/zh-cn...測試

相關文章
相關標籤/搜索