python loggingconfig.dictConfig

来源:互联网 发布:淘宝店怎么刷人气 编辑:程序博客网 时间:2024/06/11 19:30

        python中logging.config.dictConfig函数可以方便的配置自己所需要的日志系统,其官方document链接为:https://docs.python.org/2/library/logging.config.html。对于使用dictConfig函数,最难的莫非dictConfig需要的参数该如何配置了。

通用的配置结构如下。

{

'version': must,其值只能是1,  

'disable_existing_loggers': option,其值可以是True或者False,

'incremental': option,其值可以是True或者fFalse,

'formatters': {'myformatter1': {'class': must,构造formatter使用的类,字符串,必须使用全路径,比如'logging.Formatter'

                                               'format': option,formatter的格式,字符串,比如

                                               '%(levelname)s-%(message)s'

                                               'datefmt': option,日期的输出格式,字符串,比如'%Y-%m-%d %H:%M:%S'

                                                },

                    'myformatter2': {'()': must,

                                              ....,

                                             }

                   },

'filters': {'filter1': {'class': must,构造filter使用的类,字符串,必须是全路径名,比如'logging.Filter'

                          'name': option,Filter name的值

                         },

            'fitler2': {'()': must,

                          ...},

            },

'handlers': {'handler1': {'class': must,构造handler使用的类,字符串,必须使用全路径,比如'logging.StreamHandler'

                                     'level': option, handler的级别,比如'INFO'或者logging.INFO

                                     'formatter': option, handler使用的formatter,字符串名称,此值必须存在于key为'formatters'的值

                                                                   对应的dict中。比如 'myformatter1'

                                      'filters': option, handler使用的filter,是一个列表,列表中每一项是一个filter的名称且该名称必须

                                                               是'filters'的某个key,比如 ['filter1', 'filter2']

                                       ...},

  'handler2': {'()': must

                                     'level': option, 同上

                                     'formatter': option,同上 

                                      'filter': option, 同上

                                      ...},

                  },

'loggers': {'log1': {'handlers': option,logger使用的handler,是个列表,列表的每一项是一个名称字符串,且该字符串

                                                         必须存在于'handlers'对应的dict中,比如['handler1', 'handler2']。

                            'filters': option, logger使用的filter是个列表,列表的每一项是一个名称字符串,且该字符串必须存在

                                                      于'filters'对应的dict中,比如['filter1', 'filter2']

                            'level': option,logger的级别,比如'INFO'或者logging.INFO

                            'propagate': option,是否将logger消息传递给parent logger,值为True或者False

                          }

               },

'root': {'handlers': option, 同loggers

           'filters': option,同loggers

           'level': option,同loggers}

          }

}

上面通用的配置结构中,must为必须有的,option则表示可选的, '...'表示传递给所创建对象的__init__函数的参数,格式就是字典值的方式。

比如'...'表示了

'a': 'b',

'leveno': logging.INFO

则传递给相应__init__函数的额外参数为:__init__(a=b,levelno=logging.INFO)

'()'表示自定义的类,假如我在myfilter.py中实现了一个自己的MyFilter类,则'()'对应的值应该是'myfilter.MyFilter'类。

下面是一个配置的例子:mylogger.py。

<span style="font-size:14px;">#coding: utf-8import loggingimport logging.configclass SingleLevelFilter(object):    def __init__(self, pass_level):        self.pass_level = pass_level    def filter(self, record):        if self.pass_level == record.levelno:            return True        return FalseLEVEL_COLOR = {    logging.DEBUG: '\33[2;39m',    logging.INFO: '\33[0;37m',    logging.WARN: '\33[4;35m',    logging.ERROR: '\33[5;31m',    logging.FATAL: '\33[7;31m'}class ScreenHandler(logging.StreamHandler):    def emit(self, record):        try:            msg = self.format(record)            stream = self.stream            fs = LEVEL_COLOR[record.levelno] + "%s\n" + '\33[0m'            try:                if isinstance(msg, unicode) and getattr(stream, 'encoding', None):                    ufs = fs.decode(stream.encoding)                    try:                        stream.write(ufs % msg)                    except UnicodeEncodeError:                        stream.write((ufs % msg).encode(stream.encoding))                else:                    stream.write(fs % msg)            except UnicodeError:                stream.write(fs % msg.encode("UTF-8"))            self.flush()        except (KeyboardInterrupt, SystemExit):            raise        except:            self.handleError(record)def init_logger():    conf = {'version': 1,            'disable_existing_loggers': True,            'incremental': False,            'formatters': {'myformat1': {'class': 'logging.Formatter',                                         'format': '|%(asctime)s|%(name)s|%(filename)s|%(lineno)d|%(levelname)s|%(message)s',                                         'datefmt': '%Y-%m-%d %H:%M:%S'}                          },            'filters': {'filter_by_name': {'class': 'logging.Filter',                                           'name': 'logger_for_filter_name'},                        'filter_single_level_pass':{'()': 'mylogger.SingleLevelFilter',                                                    'pass_level': logging.WARN}                        },            'handlers': {'console': {'class': 'logging.StreamHandler',                                      'level': 'INFO',                                      'formatter': 'myformat1',                                      'filters': ['filter_single_level_pass', ]},                         'screen': {'()': 'mylogger.ScreenHandler',                                    'level': logging.INFO,                                    'formatter': 'myformat1',                                    'filters': ['filter_by_name', ]}                        },            'loggers': {'logger_for_filter_name': {'handlers': ['console', 'screen'],                                                   'filters': ['filter_by_name', ],                                                   'level': 'INFO'},                        'logger_for_all': {'handlers': ['console', ],                                           'filters': ['filter_single_level_pass',],                                           'level': 'INFO',                                           'propagate': False}                       }            }    logging.config.dictConfig(conf)if __name__ == '__main__':    init_logger()    logger_for_filter_name = logging.getLogger('logger_for_filter_name')    logger_for_filter_name.debug('logger_for_filter_name')    logger_for_filter_name.info('logger_for_filter_name')    logger_for_filter_name.warn('logger_for_filter_name')    logger_for_filter_name.error('logger_for_filter_name')    logger_for_filter_name.critical('logger_for_filter_name')    logger_for_all = logging.getLogger('logger_for_all')    logger_for_all.debug('logger_for_all')    logger_for_all.info('logger_for_all')    logger_for_all.warn('logger_for_all')    logger_for_all.error('logger_for_all')    logger_for_all.critical('logger_for_all')</span>

0 0
原创粉丝点击