返回顶部

收藏

自定义logging

更多
#!/usr/bin/env python
#: coding: utf-8

import logging

def initlogger(filename=None, fileformat=None, consoleformat=None):

    if not fileformat:
        fileformat = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'
    if not consoleformat:
        consoleformat = '%(name)-12s: %(levelname)-8s %(message)s'

    if filename is not None:
        fh = logging.FileHandler(filename)
        fh.setLevel(logging.DEBUG)
        fileformatter = logging.Formatter(fileformat)
        fh.setFormatter(fileformatter)
        logging.getLogger('').addHandler(fh)

    # 再创建一个handler,用于输出到控制台
    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)
    consoleformatter = logging.Formatter(consoleformat)
    ch.setFormatter(consoleformatter)
    logging.getLogger('').addHandler(ch)

if __name__ == '__main__':

    initlogger('test3.log')
    logger1 = logging.getLogger('myapp.area1')
    logger2 = logging.getLogger('myapp.area2')

    logger1.debug('Quick zephyrs blow, vexing daft Jim.')
    logger1.info('How quickly daft jumping zebras vex.')
    logger1.error('!!!!!!!!!!!!!!!!!')
    logger2.warning('Jail zesty vixen who grabbed pay from quack.')
    logger2.error('The five boxing wizards jump quickly.')

标签:python

收藏

0人收藏

支持

0

反对

0

发表评论