首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python中logging的使用(自定义日志格式)[修正bug]

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

作者头像
the5fire
发布2019-02-28 16:31:21
2.5K0
发布2019-02-28 16:31:21
举报

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

具体功能就是,定义记录日志的级别,级别从低到高打出来的日志越来越详细。这个程序中只是写了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')
    '''

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2012-11-04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档