the5fire

关注Python、Django、Vim、Linux、Web开发、团队管理和互联网--Life is short, we need Python.


python中logging的使用(自定义日志格式)[修正bug]

作者:the5fire | 标签:   | 发布:2012-11-04 9:24 p.m. | 阅读量: 12620, 12094

有网友留言想知道我在写知道创宇面试题的爬虫中怎么使用日志的,这里给贴出来,大家讨论下,不是很优雅的方式,只是能解决问题的方式。

具体功能就是,定义记录日志的级别,级别从低到高打出来的日志越来越详细。这个程序中只是写了1~5个级别。只是使用了python的logging模块。 来看代码吧:

.. code:: python

#coding=utf-8
'''
    author:huyang
    date:2012-7-17
    blog:http://www.the5fire.com
'''
import  logging
import logging.config


formatter_dict = {
    1 : logging.Formatter("%(message)s"),
    2 : logging.Formatter("%(levelname)s - %(message)s"), 
    3 : logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"),
    4 : logging.Formatter("%(asctime)s - %(levelname)s - %(message)s - [%(name)s]"),
    5 : logging.Formatter("%(asctime)s - %(levelname)s - %(message)s - [%(name)s:%(lineno)s]")
}
class Logger(object):
    def __init__(self, logname, loglevel, callfile):
        '''
            指定日志文件路径,日志级别,以及调用文件
            将日志存入到指定的文件中
        '''
        self.logger = logging.getLogger(callfile)
        self.logger.setLevel(logging.DEBUG)
        fh = logging.FileHandler(logname)

        ch = logging.StreamHandler()
        ch.setLevel(logging.ERROR)
        ch.setFormatter(formatter_dict[int(loglevel)])
        fh.setFormatter(formatter_dict[int(loglevel)])
        self.logger.addHandler(ch)
        self.logger.addHandler(fh)

    def get_logger(self):
        return self.logger


if __name__ == '__main__':
    logger = Logger(logname='hahaha', loglevel=1, callfile=__file__).get_logger()   #感谢匿名网友指正
    logger.info('test level1')
    logger1 = Logger(logname='hahaha2', loglevel=2, callfile=__file__).get_logger()
    logger1.info('test level2')
    '''
    logger2 = Logger(logname='hahaha3', loglevel=3, callfile=__file__).get_logger()
    logger2.info('test level3')
    '''
- from the5fire.com
----EOF-----

微信公众号:Python程序员杂谈


其他分类: