龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > python编程 >

python logging类库使用例子

时间:2014-11-23 02:51来源:网络整理 作者:网络 点击:
分享到:
这篇文章主要介绍了python logging类库使用例子,本文讲解了简单使用、logging的level、Handlers、FileHandler + StreamHandler等内容,需要的朋友可以参考下

一、简单使用

复制代码 代码如下:

def TestLogBasic():
    import logging
    logging.basicConfig(filename = 'log.txt', filemode = 'a', level = logging.NOTSET, format = '%(asctime)s - %(levelname)s: %(message)s')
    logging.debug('this is a message')
    logging.info("this is a info")
    logging.disable(30)#logging.WARNING
    logging.warning("this is a warnning")
    logging.critical("this is a critical issue")
    logging.error("this is a error")
    logging.addLevelName(88,"MyCustomError")
    logging.log(88,"this is an my custom error")
    try:
      raise Exception('this is a exception')
    except:
      logging.exception( 'exception')
    logging.shutdown()

TestLogBasic()

说明:(此实例为最简单的用法,用来将log记录到log文件中)

1)logging.basicConfig()中定义默认的log到log.txt,log文件为append模式,处理所有的level大于logging.NOTSET的logging,log的格式定义为'%(asctime)s - %(levelname)s: %(message)s';

2)使用logging.debug()...等来log相应level的log;

3)使用logging.disable()来disable某个logging level;

4)使用logging.addLevelName增加自定义的logging level;

5)使用logging.log来log自定义的logging level的log;

输出的text的log如下:

复制代码 代码如下:

2011-01-18 10:02:45,415 - DEBUG: this is a message
2011-01-18 10:02:45,463 - INFO: this is a info
2011-01-18 10:02:45,463 - CRITICAL: this is a critical issue
2011-01-18 10:02:45,463 - ERROR: this is a error
2011-01-18 10:02:45,463 - MyCustomError: this is an my custom error
2011-01-18 10:02:45,463 - ERROR: exception
Traceback (most recent call last):
  File "testlog.py", line 15, in TestLogBasic
    raise Exception('this is a exception')
Exception: this is a exception

二、logging的level

复制代码 代码如下:

#logging level
#logging.NOTSET 0
#logging.DEBUG 10
#logging.INFO 20
#logging.WARNING 30
#logging.ERROR 40
#logging.CRITICAL 50

logging的level对应于一个int,例如10,20...用户可以自定义logging的level。

可以使用logging.setLevel()来指定要处理的logger级别,例如my_logger.setLevel(logging.DEBUG)表示只处理logging的level大于10的logging。
 

三、Handlers

Handler定义了log的存储和显示方式。

NullHandler不做任何事情。

StreamHandler实例发送错误到流(类似文件的对象)。
FileHandler实例发送错误到磁盘文件。
BaseRotatingHandler是所有轮徇日志的基类,不能直接使用。但是可以使用RotatingFileHandler和TimeRotatingFileHandler。
RotatingFileHandler实例发送信息到磁盘文件,并且限制最大的日志文件大小,并适时轮徇。
TimeRotatingFileHandler实例发送错误信息到磁盘,并在适当的事件间隔进行轮徇。
SocketHandler实例发送日志到TCP/IP socket。
DatagramHandler实例发送错误信息通过UDP协议。
SMTPHandler实例发送错误信息到特定的email地址。
SysLogHandler实例发送日志到UNIX syslog服务,并支持远程syslog服务。
NTEventLogHandler实例发送日志到WindowsNT/2000/XP事件日志。
MemoryHandler实例发送日志到内存中的缓冲区,并在达到特定条件时清空。
HTTPHandler实例发送错误信息到HTTP服务器,通过GET或POST方法。
NullHandler,StreamHandler和FileHandler类都是在核心logging模块中定义的。其他handler定义在各个子模块中,叫做logging.handlers。

当然还有一个logging.config模块提供了配置功能。

四、FileHandler + StreamHandler

复制代码 代码如下:

def TestHanderAndFormat():
    import logging
    logger = logging.getLogger("simple")
    logger.setLevel(logging.DEBUG)
   
    # create file handler which logs even debug messages
    fh = logging.FileHandler("simple.log")
    fh.setLevel(logging.DEBUG)
   
    # create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel(logging.ERROR)
   
    # create formatter and add it to the handlers
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    ch.setFormatter(formatter)
    fh.setFormatter(formatter)
   
    # add the handlers to logger
    logger.addHandler(ch)
    logger.addHandler(fh)

精彩图集

赞助商链接