码迷,mamicode.com
首页 > 编程语言 > 详细

python常用模块之logging模块

时间:2017-08-20 16:59:12      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:tool   hand   class   ret   imp   大于   line   war   evel   

---恢复内容开始---

一、logging模块的作用以及两种用法

   logging模块看名字就知道是用来写日志的,以前我们写日志需要自己往文件里写记录信息,使用了logging之后我们只需要一次配置好,以后写日志的事情都不需要我们操心了,非常方便。logging模块有两种使用方法,一种是简单的函数式,另一种是用logging对象的方式,对象的方式使用起来功能更全更灵活,所以使用最多的也是对象的方式。

 

  二、函数式配置

  

技术分享

 

import logging  
logging.basicConfig(level=logging.DEBUG,  #不配置默认只输出级别大于等于waring的日志
                    format=‘%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s‘,  
                    datefmt=‘%a, %d %b %Y %H:%M:%S‘,  
                    filename=‘/tmp/test.log‘,  
                    filemode=‘w‘)  
  
logging.debug(‘debug message‘)  
logging.info(‘info message‘)  
logging.warning(‘warning message‘)  
logging.error(‘error message‘)  
logging.critical(‘critical message‘)

 

技术分享

basicConfig可用参数

技术分享 View Code

format参数可用的格式化字符串

技术分享 View Code

 

 三、logger对象配置

  

技术分享
import logging
def my_logger(filename,file=True,stream=True):
    ‘‘‘日志函数‘‘‘
    logger=logging.getLogger() #日志对象
    formatter = logging.Formatter(fmt=‘%(asctime)s -- %(message)s‘,
                                  datefmt=‘%d/%m/%Y %H:%M:%S‘)  # 日志格式
    logger.setLevel(logging.DEBUG)  # 日志级别

    if file:
        file_handler=logging.FileHandler(filename,encoding=‘utf-8‘) #文件流(文件操作符)
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)

    if stream:
        stream_handler=logging.StreamHandler()  #屏幕流(屏幕操作符)
        stream_handler.setFormatter(formatter)
        logger.addHandler(stream_handler)
    return logger

logger=my_logger(‘log‘)
logging.debug(‘出错了‘)

---恢复内容结束---

python常用模块之logging模块

标签:tool   hand   class   ret   imp   大于   line   war   evel   

原文地址:http://www.cnblogs.com/lianxuebin/p/7400166.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!