您的位置:首页 > 编程语言 > Python开发

Python打印log,包括行号,路径,方法名,文件

2013-07-18 11:09 531 查看
logger.py 文件

#!/usr/bin/python
 # coding: utf-8
  
 import logging
 import logging.handlers
 from logging import *
 from datetime import *
 
 logger = logging.getLogger()
 logger.setLevel(logging.DEBUG)
 
 rht = logging.handlers.TimedRotatingFileHandler("reindex_out.log", 'D')
 fmt = logging.Formatter("%(asctime)s %(pathname)s %(filename)s %(funcName)s %(lineno)s \
      %(levelname)s - %(message)s", "%Y-%m-%d %H:%M:%S")
 rht.setFormatter(fmt)
 logger.addHandler(rht)
 
 debug = logger.debug
 info = logger.info
 warning = logger.warn
 error = logger.error
 critical = logger.critical


测试脚本

#!/usr/bin/env python
# coding utf-8
 
from logger import *
import sys
import os
 
info("log from logger info")

debug("this is from test.py")
print 'current dir is ' + os.getcwd()


format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:

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


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

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

[thead]
[/thead]

级别对应的值
CRITICAL50
ERROR40
WARNING30
INFO20
DEBUG10
NOTSET0
可以给日志对象(Logger Instance)设置日志级别,低于该级别的日志消息将会被忽略,也可以给Hanlder设置日志级别,对于低于该级别的日志消息, Handler也会忽略。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: