python 中关于logging 日志的输出设定

  1. #!/usr/bin/python  
  2. # coding: utf-8  
  3.    
  4. import logging  
  5. import logging.handlers  
  6. from logging import *  
  7. from datetime import *  
  8.   
  9. logger = logging.getLogger()  
  10. logger.setLevel(logging.DEBUG)  
  11.   
  12. rht = logging.handlers.TimedRotatingFileHandler("reindex_out.log", 'D')  
  13. fmt = logging.Formatter("%(asctime)s %(pathname)s %(filename)s %(funcName)s %(lineno)s \  
  14.      %(levelname)s - %(message)s", "%Y-%m-%d %H:%M:%S")  
  15. rht.setFormatter(fmt)  
  16. logger.addHandler(rht)  
  17.   
  18. debug = logger.debug  
  19. info = logger.info  
  20. warning = logger.warn  
  21. error = logger.error  
  22. critical = logger.critical  

 

  1. #!/usr/bin/env python  
  2. # coding utf-8  
  3.    
  4. from logger import *  
  5. import sys  
  6. import os  
  7.    
  8. info("log from logger info")  
  9.   
  10. debug("this is from test.py")  
  11. print 'current dir is ' + os.getcwd()

 format: 指定输出的格式和内容,format能够输出不少有用信息,如上例所示:python

  1. %(levelno)s:         打印日志级别的数值  
  2.  %(levelname)s:    打印日志级别名称  
  3.  %(pathname)s:    打印当前执行程序的路径,其实就是sys.argv[0]  
  4.  %(filename)s:      打印当前执行程序名  
  5.  %(funcName)s:    打印日志的当前函数  
  6.  %(lineno)d:         打印日志的当前行号  
  7.  %(asctime)s:      打印日志的时间  
  8.  %(thread)d:        打印线程ID  
  9.  %(threadName)s: 打印线程名称  
  10.  %(process)d:      打印进程ID  
  11.  %(message)s:    打印日志信息 

datefmt: 指定时间格式,同time.strftime()函数

level: 设置日志级别,默认为logging.WARNINGthis

 

级别 对应的值
CRITICAL 50
ERROR 40
WARNING 30
INFO 20
DEBUG 10
NOTSET 0

 

能够给日志对象(Logger Instance)设置日志级别,低于该级别的日志消息将会被忽略,也能够给Hanlder设置日志级别,对于低于该级别的日志消息, Handler也会忽略。线程

相关文章
相关标签/搜索