Python标准模块logging
http://blog.csdn.net/fxjtoday/article/details/6307285
开发Python, 一直以来都是使用自己编写的logging模块. 比较土......
今天发现python的标准模块的这个功能做的挺好, 记录一下, 以后使用模块来进行logging.
对于这个模块的介绍网上也很多, 我也不用自己写了, 比较好的如下,
http://crazier9527.iteye.com/blog/290018 Python的标准logging模块
http://blog.endlesscode.com/2010/06/03/python-logging-module/ Python的logging模块
http://docs.python.org/library/logging.html 官方文档
下面就对于在项目中比较需要用到的部分摘录一些,
简单的例子
- import logging
- import sys
- logger = logging.getLogger("endlesscode")
- formatter = logging.Formatter('%(name)-12s %(asctime)s %(levelname)-8s %(message)s', '%a, %d %b %Y %H:%M:%S',)
- file_handler = logging.FileHandler("test.log")
- file_handler.setFormatter(formatter)
- stream_handler = logging.StreamHandler(sys.stderr)
- logger.addHandler(file_handler)
- logger.addHandler(stream_handler)
- #logger.setLevel(logging.ERROR)
- logger.error("fuckgfw")
- logger.removeHandler(stream_handler)
- logger.error("fuckgov")
上面这段代码基本包含logging模块的基本feature
GetLogger
GetLogger() returns a reference to a logger instance with the specified name if it is provided, or root if not. The names are period-separated hierarchical structures. Multiple calls to getLogger() with the same name will return a reference to the same logger object.
后面会看到这种以'.'分隔的hierarchical structures有什么用.
Formatter
Formatter对象定义了最终log信息的顺序,结构和内容, 后面会详细解释.
Handler
这儿用到了StreamHandler和FileHandler, 用于向不同的输出端打log.
SetLevel
Logging有如下级别: DEBUG,INFO,WARNING,ERROR,CRITICAL
默认级别是WARNING, logging模块只会输出指定level以上的log
这样的好处, 就是在项目开发时debug用的log, 在产品release阶段不用一一注释, 只需要调整logger的级别就可以了, 很方便的.
Formatter
Formatter对象定义了最终log信息的顺序,结构和内容.于基本的logging.Handler类不同,应用可以直接实例化formatter类,当然,如果需要你也可以子例化formatter以便定制它的一些行为.构造函数接受两个可选参数:一个信息格式字符串和一个日期格式字符串.如果没有信息格式字符串,直接输出log信息.如果没有日期格式字符串,默认的格式是:%Y-%m-%d %H:%M:%S
上面的代码给出了Formatter的例子, 下面表格给出所有可以使用的format,

Handler
Logging包含很多handler, 可能用到的有下面几种
- StreamHandler instances send error messages to streams (file-like objects).
- FileHandler instances send error messages to disk files.
- RotatingFileHandler instances send error messages to disk files, with support for maximum log file sizes and log file rotation.
- TimedRotatingFileHandler instances send error messages to disk files, rotating the log file at certain timed intervals.
- SocketHandler instances send error messages to TCP/IP sockets.
- DatagramHandler instances send error messages to UDP sockets.
- SMTPHandler instances send error messages to a designated email address.
最常用的也就是StreamHandler和FileHandler
Configuration
- Creating loggers, handlers, and formatters explicitly using Python code that calls the configuration methods listed above.
- Creating a logging config file and reading it using the fileConfig() function.
- Creating a dictionary of configuration information and passing it to the dictConfig() function.
第一种配置方法前面的code里面已经有了
第二种配置方法, 我觉得在项目里面是比较实用的, 通过编写配置文件, 在code里面只需要用fileConfig配置一下logging, 显得比较简洁.
这个可以参照http://crazier9527.iteye.com/blog/290026 或 官方文档.
Multiple handlers and formatters
Loggers是一个简单的Python对象.addHandler()方法没有最多或者最少配额,当你的应用需要在把所有的log信息打到一个txt文件中去,同时又需要把errors级别一上的错误信息打到console时,你就会体会到这个特性的好处.只要简单的配置一下合适的handlers就可以实现这个功能.应用对logging的调用用不着修改.以下是对前一个基于module的配置例子的改进:
- import logging
- logger = logging.getLogger("simple_example")
- logger.setLevel(logging.DEBUG)
- # create file handler which logs even debug messages
- fh = logging.FileHandler("spam.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")
多module使用Logging(只要在同一个Python interpreter process)
上面我曾提到过,所有的对logging.getLogger(‘someLogger’)的调用都会返回同一个对象.这个规则不仅仅在同一个module有效,而且对在同一个Python的解释器进程里面的多个module也有效.而且,应用代码可以在一个module里面定义一个父logger,而在另一个module里面继承这个logger,所有对这个子logger的调用都会转到父logger里面去,如下所示:
下面这个是主模块的代码,
- import logging
- import auxiliary_module
- # create logger with "spam_application"
- logger = logging.getLogger("spam_application")
- logger.setLevel(logging.DEBUG)
- # create file handler which logs even debug messages
- fh = logging.FileHandler("spam.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")
- fh.setFormatter(formatter)
- ch.setFormatter(formatter)
- # add the handlers to the logger
- logger.addHandler(fh)
- logger.addHandler(ch)
- logger.info("creating an instance of auxiliary_module.Auxiliary")
- a = auxiliary_module.Auxiliary()
- logger.info("created an instance of auxiliary_module.Auxiliary")
- logger.info("calling auxiliary_module.Auxiliary.do_something")
- a.do_something()
- logger.info("finished auxiliary_module.Auxiliary.do_something")
- logger.info("calling auxiliary_module.some_function()")
- auxiliary_module.some_function()
- logger.info("done with auxiliary_module.some_function()")
这个是子模块的代码,
- import logging
- # create logger
- module_logger = logging.getLogger("spam_application.auxiliary")
- class Auxiliary:
- def __init__(self):
- self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
- self.logger.info("creating an instance of Auxiliary")
- def do_something(self):
- self.logger.info("doing something")
- a = 1 + 1
- self.logger.info("done doing something")
- def some_function():
- module_logger.info("received a call to /"some_function/"")
可以看到, 我们在主模块里面定义了一个logger 'spam_application', 并对他进行了配置.
那么在这个解释器进程里面的任何地方去通过getLogger('spam_application')得到的对象都是一样的, 不需要从新定义配置, 可以直接使用.
更方便的是, 你定义任意该logger的子logger, 都可以共享父logger的定义和配置
所谓的父子logger只是简单的通过命名来识别, 任意以'spam_application.'开头的logger都是他的子logger, 例如'spam_application.auxiliary'
这个在实际的开发中, 还是很方便的, 对于一个application,
首先通过logging配置文件编写好这个application所对应的log策略, 可以只生成一个根logger, 比如叫'Project'
然后在Main函数里面, 通过fileConfig加载logging的配置
接着在appliction的任意地方, 不同的模块中, 可以使用Project的子logger, 如Project.UI, Project.Core, 来进行log, 并且不需要反复的定义和配置各个logger.
Python标准模块logging的更多相关文章
- Python标准模块--logging
1 logging模块简介 logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级.日志保存路径.日志文件回滚等:相比print,具备如下优点: 可以通过设置不同 ...
- Python标准模块--logging(转载)
转载地址:http://www.cnblogs.com/zhbzz2007/p/5943685.html#undefined Python标准模块--logging 1 logging模块简介 log ...
- Python标准模块--threading
1 模块简介 threading模块在Python1.5.2中首次引入,是低级thread模块的一个增强版.threading模块让线程使用起来更加容易,允许程序同一时间运行多个操作. 不过请注意,P ...
- python日志模块logging
python日志模块logging 1. 基础用法 python提供了一个标准的日志接口,就是logging模块.日志级别有DEBUG.INFO.WARNING.ERROR.CRITICAL五种( ...
- Python标准模块--importlib
作者:zhbzz2007 出处:http://www.cnblogs.com/zhbzz2007 欢迎转载,也请保留这段声明.谢谢! 1 模块简介 Python提供了importlib包作为标准库的一 ...
- 【转】Python标准模块--importlib
[转]Python标准模块--importlib 作者:zhbzz2007 出处:http://www.cnblogs.com/zhbzz2007 欢迎转载,也请保留这段声明.谢谢! 1 模块简介 P ...
- Thread类的其他方法,同步锁,死锁与递归锁,信号量,事件,条件,定时器,队列,Python标准模块--concurrent.futures
参考博客: https://www.cnblogs.com/xiao987334176/p/9046028.html 线程简述 什么是线程?线程是cpu调度的最小单位进程是资源分配的最小单位 进程和线 ...
- python 全栈开发,Day42(Thread类的其他方法,同步锁,死锁与递归锁,信号量,事件,条件,定时器,队列,Python标准模块--concurrent.futures)
昨日内容回顾 线程什么是线程?线程是cpu调度的最小单位进程是资源分配的最小单位 进程和线程是什么关系? 线程是在进程中的 一个执行单位 多进程 本质上开启的这个进程里就有一个线程 多线程 单纯的在当 ...
- python全栈开发,Day42(Thread类的其他方法,同步锁,死锁与递归锁,信号量,事件,条件,定时器,队列,Python标准模块--concurrent.futures)
昨日内容回顾 线程 什么是线程? 线程是cpu调度的最小单位 进程是资源分配的最小单位 进程和线程是什么关系? 线程是在进程中的一个执行单位 多进程 本质上开启的这个进程里就有一个线程 多线程 单纯的 ...
随机推荐
- 20.springboot项目部署到linux服务器文件上传临时路径处理问题
1.前言 把项目部署到服务器上之后,文件上传默认会在/tmp路径中. 之前想了各种解决办法,比如如何更改这个上传路径...... 最后发现不是个好的方法,当然就想到了更好的解决方案. 就是我把上传文件 ...
- ATK系列库说明
初衷 重构和复用是软件的一个古老话题. 在日常的软件项目开发的过程序中,如何保证团队代码的强健,同时在不断变化的需过程中最大限度的保障代码的一致性,是项目开发中的难以控制的,我们可以借助各种源码管理和 ...
- sqlServer2014安装说明(windows7 64位)
SqlServer2014安装说明(windows7 64位) 地址:https://www.microsoft.com/zh-cn/download/details.aspx?id=42299 1, ...
- C++中vector,set,map自定义排序
一.vector排序 vector支持cmp,就类似数组,可以直接sort. #include <iostream> #include <algorithm> #include ...
- Percona-Tookit工具包之pt-table-checksum
Preface The master-slave replication is commonly used in our product evironment.On account o ...
- 使用Ansible实现nginx+keepalived高可用负载均衡自动化部署
本篇文章记录通过Ansible自动化部署nginx的负载均衡高可用,前端代理使用nginx+keepalived,端web server使用3台nginx用于负载效果的体现,结构图如下: 部署前准备工 ...
- 【linux下dhcp服务的简单搭建及优化部署】
dhcp server: 1::vim /etc/sysconfig/network-scripts/ifcfg-scfg:配置 server的 static IP: 2:vim /etc/dhcpd ...
- QQ群排名优化到霸屏的策略怎么做?
谈起QQ群排名霸屏,首先要弄清楚概念,有些刚接触QQ群的朋友可能不太了解,所谓的QQ群排名霸屏,就是指当你的客户群体搜索QQ群某个关键词时,出现在QQ群搜索结果前面的群,全部或者大部分都是我们自己的群 ...
- flask 中访问时后台错误 error: [Errno 32] Broken pipe
解决办法:app.run(threaded=True) 个人理解:flask默认单线程,访问一个页面时会访问到很多页面,比如一些图片,加入参数使其为多线程
- Python3爬虫(六) 解析库的使用之Beautiful Soup
Infi-chu: http://www.cnblogs.com/Infi-chu/ Beautiful Soup 借助网页的结构和属性等特性来解析网页,这样就可以省去复杂的正则表达式的编写. Bea ...