Python 配置日志

Python 2.6+

def cfgLogging():
    from logging.handlers import RotatingFileHandler
    console = logging.StreamHandler()
    console.setLevel(logging.DEBUG)
    Rthandler = RotatingFileHandler('/var/log/abc.log', maxBytes=10*1024*1024,backupCount=5)
    Rthandler.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s %(name)-12s: %(levelname)-8s | %(message)s')
    Rthandler.setFormatter(formatter)
    console.setFormatter(formatter)
    mainlogger = logging.getLogger('')
    mainlogger.addHandler(Rthandler) 
    mainlogger.addHandler(console) 
    mainlogger.setLevel(logging.INFO)

Python2.7+

#coding:utf-8

import logging.config


def cfgLogging():
    LOGGING = {
               'version': 1,
               'disable_existing_loggers': True,
               'formatters': {
                              'default': {'format': '[%(asctime)-25s] [%(relativeCreated)-15s] %(name)-12s pid:%(process)d %(message)s'},
                               # default': {
                               #           'format' : '%(asctime)s %(message)s',
                               #           'datefmt' : '%Y-%m-%d %H:%M:%S'
                               # }
                },
               'handlers': {
                            'console':{
                                       'level':'DEBUG',
                                       'class':'logging.StreamHandler',
                                       'formatter': 'default'
                            },
                            'file': {
                                     'level': 'DEBUG',
                                     'class': 'logging.handlers.RotatingFileHandler',
                                     'formatter': 'default',
                                     'filename' : 'runlog.log',
                                     'maxBytes':    20 * 1024 * 1024,  # 10M
                                     'backupCount': 5,
                                     'encoding' : 'utf8',
                            }
                },
               'loggers' : {
                            # 定义了一个logger
                            '' : {
                                          'level' : 'DEBUG',
                                          'handlers' : ['console', 'file'],
                                          'propagate' : True
                            }
                }
    }
    logging.config.dictConfig(LOGGING)
原文地址:https://www.cnblogs.com/morya/p/4888684.html