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将多个文本文件合并为一个文本的代码(便于搜索)
Mar 13 Python
用yum安装MySQLdb模块的步骤方法
Dec 15 Python
Python简单实现的代理服务器端口映射功能示例
Apr 08 Python
python批量爬取下载抖音视频
Jun 17 Python
python 整数越界问题详解
Jun 27 Python
Python_查看sqlite3表结构,查询语句的示例代码
Jul 17 Python
JetBrains PyCharm(Community版本)的下载、安装和初步使用图文教程详解
Mar 19 Python
Windows下Anaconda安装、换源与更新的方法
Apr 17 Python
Python unittest装饰器实现原理及代码
Sep 08 Python
python树莓派通过队列实现进程交互的程序分析
Jul 04 Python
Pygame Rect区域位置的使用(图文)
Nov 17 Python
python机器学习实现oneR算法(以鸢尾data为例)
Mar 03 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
destoon实现调用热门关键字的方法
2014/07/15 PHP
PHP实现linux命令tail -f
2016/02/22 PHP
php mysql 封装类实例代码
2016/09/18 PHP
php中__toString()方法用法示例
2016/12/07 PHP
说明你的Javascript技术很烂的五个原因
2011/04/26 Javascript
js数组循环遍历数组内所有元素的方法
2014/01/18 Javascript
jQuery简单图表peity.js使用示例
2014/05/02 Javascript
javascript生成不重复的随机数
2015/07/17 Javascript
JavaScript事件代理和委托详解
2016/04/08 Javascript
JS实现倒计时(天数、时、分、秒)
2016/11/16 Javascript
JavaScript设计模式之策略模式详解
2017/06/09 Javascript
springmvc接收jquery提交的数组数据代码分享
2017/10/28 jQuery
webstorm和.vue中es6语法报错的解决方法
2018/05/08 Javascript
JavaScript 禁止用户保存图片的实现代码
2020/04/28 Javascript
使用vue实现通过变量动态拼接url
2020/07/22 Javascript
浅谈Vue使用Cascader级联选择器数据回显中的坑
2020/10/31 Javascript
用实例详解Python中的Django框架中prefetch_related()函数对数据库查询的优化
2015/04/01 Python
Python+Django搭建自己的blog网站
2018/03/13 Python
解决python中遇到字典里key值为None的情况,取不出来的问题
2018/10/17 Python
使用 Python 处理 JSON 格式的数据
2019/07/22 Python
Python unittest框架操作实例解析
2020/04/13 Python
PyQt5如何将.ui文件转换为.py文件的实例代码
2020/05/26 Python
Python 字典中的所有方法及用法
2020/06/10 Python
Python中使用aiohttp模拟服务器出现错误问题及解决方法
2020/10/31 Python
TripAdvisor日本:全球领先的旅游网站
2019/02/14 全球购物
法国隐形眼镜网站:VisionDirect.fr
2020/03/03 全球购物
alice McCALL官网:澳大利亚时尚品牌
2020/11/16 全球购物
中专毕业生的自我鉴定
2013/12/01 职场文书
公务员职业生涯规划书范文  
2014/01/19 职场文书
公司廉洁自律承诺书
2014/03/27 职场文书
献爱心活动总结
2014/05/07 职场文书
导游词之杭州岳王庙
2019/11/13 职场文书
jquery插件实现搜索历史
2021/04/24 jQuery
如何使用PostgreSQL进行中文全文检索
2021/05/27 PostgreSQL
Java Spring Boot 正确读取配置文件中的属性的值
2022/04/20 Java/Android
Android实现获取短信验证码并自动填充
2023/05/21 Java/Android