- #!/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
级别 | 对应的值 |
---|---|
CRITICAL | 50 |
ERROR | 40 |
WARNING | 30 |
INFO | 20 |
DEBUG | 10 |
NOTSET | 0 |
可以给日志对象(Logger Instance)设置日志级别,低于该级别的日志消息将会被忽略,也可以给Hanlder设置日志级别,对于低于该级别的日志消息, Handler也会忽略。