python logging类库使用例子


Posted in Python onNovember 22, 2014

一、简单使用

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)
    # "application" code

    logger.debug("debug message")

    logger.info("info message")

    logger.warn("warn message")

    logger.error("error message")

    logger.critical("critical message")
TestHanderAndFormat()

说明:(此实例同时使用FileHandler和StreamHandler来实现同时将log写到文件和console)

1)使用logging.getLogger()来新建命名logger;

2)使用logging.FileHandler()来生成FileHandler来将log写入log文件,使用logger.addHandler()将handler与logger绑定;

3)使用logging.StreamHandler()来生成StreamHandler来将log写到console,使用logger.addHandler()将handler与logger绑定;

4)使用logging.Formatter()来构造log格式的实例,使用handler.setFormatter()来将formatter与handler绑定;

 运行结果

simple.txt

2011-01-18 11:25:57,026 - simple - DEBUG - debug message

2011-01-18 11:25:57,072 - simple - INFO - info message

2011-01-18 11:25:57,072 - simple - WARNING - warn message

2011-01-18 11:25:57,072 - simple - ERROR - error message

2011-01-18 11:25:57,072 - simple - CRITICAL - critical message

console

2011-01-18 11:25:57,072 - simple - ERROR - error message

2011-01-18 11:25:57,072 - simple - CRITICAL - critical message

五、RotatingFileHandler

def TestRotating():

    import glob

    import logging

    import logging.handlers

    

    LOG_FILENAME = 'logging_rotatingfile_example.out'
    # Set up a specific logger with our desired output level

    my_logger = logging.getLogger('MyLogger')

    my_logger.setLevel(logging.DEBUG)
    # Add the log message handler to the logger

    handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=20, backupCount=5)
    my_logger.addHandler(handler)
    # Log some messages

    for i in range(20):

        my_logger.debug('i = %d' % i)
    # See what files are created

    logfiles = glob.glob('%s*' % LOG_FILENAME)
    for filename in logfiles:

        print(filename)

        

TestRotating()

说明:

RotatingFileHandler指定了单个log文件的size的最大值和log文件的数量的最大值,如果文件大于最大值,将分割为多个文件,如果log文件的数量多于最多个数,最老的log文件将被删除。例如此例中最新的log总是在logging_rotatingfile_example.out,logging_rotatingfile_example.out.5中包含了最老的log。

运行结果:

logging_rotatingfile_example.out

logging_rotatingfile_example.out.1

logging_rotatingfile_example.out.2

logging_rotatingfile_example.out.3

logging_rotatingfile_example.out.4

logging_rotatingfile_example.out.5

六、使用fileConfig来使用logger

import logging

import logging.config
logging.config.fileConfig("logging.conf")
# create logger

logger = logging.getLogger("simpleExample")
# "application" code

logger.debug("debug message")

logger.info("info message")

logger.warn("warn message")

logger.error("error message")

logger.critical("critical message")

logging.conf文件如下:

[loggers]

keys=root,simpleExample
[handlers]

keys=consoleHandler
[formatters]

keys=simpleFormatter
[logger_root]

level=DEBUG

handlers=consoleHandler
[logger_simpleExample]

level=DEBUG

handlers=consoleHandler

qualname=simpleExample

propagate=0
[handler_consoleHandler]

class=StreamHandler

level=DEBUG

formatter=simpleFormatter

args=(sys.stdout,)
[formatter_simpleFormatter]

format=%(asctime)s - %(name)s - %(levelname)s - %(message)s

datefmt=

运行结果:

2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message

2005-03-19 15:38:55,979 - simpleExample - INFO - info message

2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message

2005-03-19 15:38:56,055 - simpleExample - ERROR - error message

2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
Python 相关文章推荐
python重试装饰器示例
Feb 11 Python
Python写的PHPMyAdmin暴力破解工具代码
Aug 06 Python
python获取指定时间差的时间实例详解
Apr 11 Python
Python Selenium Cookie 绕过验证码实现登录示例代码
Apr 10 Python
Python2与Python3的区别实例总结
Apr 17 Python
Python Matplotlib 基于networkx画关系网络图
Jul 10 Python
Python及Pycharm安装方法图文教程
Aug 05 Python
Django 博客实现简单的全文搜索的示例代码
Feb 17 Python
Python3 ID3决策树判断申请贷款是否成功的实现代码
May 21 Python
解决import tensorflow导致jupyter内核死亡的问题
Feb 06 Python
Python NumPy灰度图像的压缩原理讲解
Aug 04 Python
Python OpenCV超详细讲解读取图像视频和网络摄像头
Apr 02 Python
Python中模拟enum枚举类型的5种方法分享
Nov 22 #Python
Python读写Excel文件方法介绍
Nov 22 #Python
Python中的包和模块实例
Nov 22 #Python
Python动态加载模块的3种方法
Nov 22 #Python
收集的几个Python小技巧分享
Nov 22 #Python
Python获取Windows或Linux主机名称通用函数分享
Nov 22 #Python
Python中使用glob和rmtree删除目录子目录及所有文件的例子
Nov 21 #Python
You might like
用PHP和ACCESS写聊天室(四)
2006/10/09 PHP
PHP教程之PHP中shell脚本的使用方法分享
2012/02/23 PHP
php实现用于计算执行时间的类实例
2015/04/18 PHP
json跟xml的对比分析
2008/06/10 Javascript
JS getStyle获取最终样式函数代码
2010/04/01 Javascript
ExtJs Excel导出并下载IIS服务器端遇到的问题
2011/09/16 Javascript
js通过googleAIP翻译PHP系统的语言配置的实现代码
2011/10/17 Javascript
jQuery中$.fn的用法示例介绍
2013/11/05 Javascript
node.js中的socket.io的广播消息
2014/12/15 Javascript
JS+HTML5实现的前端购物车功能插件实例【附demo源码下载】
2016/10/17 Javascript
Vue.js常用指令的使用小结
2017/06/23 Javascript
protractor的安装与基本使用教程
2017/07/07 Javascript
微信小程序实现跟随菜单效果和循环嵌套加载数据
2017/11/21 Javascript
Vue结合Video.js播放m3u8视频流的方法示例
2018/05/04 Javascript
nodejs 简单实现动态html的方法
2018/05/12 NodeJs
JavaScript静态作用域和动态作用域实例详解
2019/06/17 Javascript
python创建一个最简单http webserver服务器的方法
2015/05/08 Python
Python实现给文件添加内容及得到文件信息的方法
2015/05/28 Python
python 创建弹出式菜单的实现代码
2017/07/11 Python
python 3.5实现检测路由器流量并写入txt的方法实例
2017/12/17 Python
Python实现的根据IP地址计算子网掩码位数功能示例
2018/05/23 Python
对python中Json与object转化的方法详解
2018/12/31 Python
python实现字典嵌套列表取值
2019/12/16 Python
python如何爬取网页中的文字
2020/07/28 Python
pycharm 快速解决python代码冲突的问题
2021/01/15 Python
纯CSS实现右侧底部悬浮效果(悬浮QQ、微信、微博、邮箱等联系方式)
2015/04/24 HTML / CSS
美国知名艺术画网站:Art.com
2017/02/09 全球购物
俄罗斯韩国化妆品网上商店:Cosmasi.ru
2019/10/31 全球购物
Shell如何接收变量输入
2012/09/24 面试题
某公司部分笔试题
2013/11/05 面试题
18岁生日感言
2014/01/12 职场文书
优秀研究生主要事迹
2014/06/03 职场文书
公司的门卫岗位职责
2014/09/09 职场文书
客户答谢会致辞
2015/01/20 职场文书
2016先进工作者事迹材料
2016/02/25 职场文书
Flutter Navigator 实现路由传递参数
2022/04/22 Java/Android