Python logging 分级日志,按照日志优先等级,分别记录日志到不同等级的文件中。

日志等级:

CRITICAL = FATAL > ERROR > WARNING = WARN > INFO > DEBUG > NOTSET

 

记录日志到文件:

python-logging-level

 

代码示例:

文件: common/logger.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# copyright by mimvp.com

'''
日志分级过滤

CRITICAL = FATAL > ERROR > WARNING = WARN > INFO > DEBUG > NOTSET
'''

import os
import logging
from logging.handlers import RotatingFileHandler


class LevelFilter(logging.Filter):
    def __init__(self, name):
        self.name = name
    
    def filter(self, record):
        return record.levelno == self.name
        

class Logger(object):
    LOGGER_FILE_DIR = 'logs'
    LOGGER_FILE_NAME = 'cibn_videodown.log'
    LOGGER_FILE = os.path.join(LOGGER_FILE_DIR, LOGGER_FILE_NAME)
    
    if not os.path.exists(LOGGER_FILE_DIR):
        os.makedirs(LOGGER_FILE_DIR)
        
    _fmt = logging.Formatter("%(message)s")

    _consoleHandler = logging.StreamHandler()
    _consoleHandler.setFormatter(_fmt)
    
    _debugHandler = RotatingFileHandler(filename=LOGGER_FILE+'._debug', maxBytes=1024*1024*1024, backupCount=5)
    _debugHandler.setFormatter(_fmt)
    _debugHandler.addFilter(LevelFilter(logging.DEBUG))
    
    _infoHandler = RotatingFileHandler(filename=LOGGER_FILE+'._info', maxBytes=1024*1024*1024, backupCount=5)
    _infoHandler.setFormatter(_fmt)
    _infoHandler.addFilter(LevelFilter(logging.INFO))
    
    _warnHandler = RotatingFileHandler(filename=LOGGER_FILE+'._warn', maxBytes=1024*1024*1024, backupCount=5)
    _warnHandler.setFormatter(_fmt)
    _warnHandler.addFilter(LevelFilter(logging.WARN))
    
    _errorHandler = RotatingFileHandler(filename=LOGGER_FILE+'._error', maxBytes=1024*1024*1024, backupCount=5)
    _errorHandler.setFormatter(_fmt)
    _errorHandler.addFilter(LevelFilter(logging.ERROR))
    
    _fatalHandler = RotatingFileHandler(filename=LOGGER_FILE+'._fatal', maxBytes=1024*1024*1024, backupCount=5)
    _fatalHandler.setFormatter(_fmt)
    _fatalHandler.addFilter(LevelFilter(logging.FATAL))
    
    
    @classmethod
    def _set_use_fmt(cls):
        _fmt = logging.Formatter("%(asctime)-15s (%(name)s) - %(filename)s [line : %(lineno)d] %(levelname)-8s: %(message)s")
        
        Logger._consoleHandler.setFormatter(_fmt)
        Logger._debugHandler.setFormatter(_fmt)
        Logger._infoHandler.setFormatter(_fmt)
        Logger._warnHandler.setFormatter(_fmt)
        Logger._errorHandler.setFormatter(_fmt)
        Logger._fatalHandler.setFormatter(_fmt)
    
    
    @classmethod
    def get_logger(cls, name, level=logging.DEBUG, use_fmt=True):
        if use_fmt:
            Logger._set_use_fmt()
        
        _logger = logging.getLogger(name)
        _logger.addHandler(Logger._consoleHandler)
        _logger.addHandler(Logger._debugHandler)
        _logger.addHandler(Logger._infoHandler)
        _logger.addHandler(Logger._warnHandler)
        _logger.addHandler(Logger._errorHandler)
        _logger.addHandler(Logger._fatalHandler)
        _logger.setLevel(level)
        return _logger
            
            
if __name__ == '__main__':
    logger = Logger.get_logger('Logger')
#     logger = Logger.get_logger('Logger', use_fmt=False)
    
    logger.debug('i am debug')
    logger.info('i am info')
    logger.warn('i am warn')
    logger.error('i am error')
    logger.fatal('i am fatal')

 

运行结果:

2015-04-13 16:19:19,234 (Logger) - logger.py [line : 89] DEBUG   : i am debug
2015-04-13 16:19:19,234 (Logger) - logger.py [line : 90] INFO    : i am info
2015-04-13 16:19:19,235 (Logger) - logger.py [line : 91] WARNING : i am warn
2015-04-13 16:19:19,235 (Logger) - logger.py [line : 92] ERROR   : i am error
2015-04-13 16:19:19,235 (Logger) - logger.py [line : 93] CRITICAL: i am fatal

 

 

参考推荐:

Python 日志logging实例

Tornado源码分析之Logging