开发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, 可能用到的有下面几种

  1. StreamHandler instances send error messages to streams (file-like objects).
  2. FileHandler instances send error messages to disk files.
  3. RotatingFileHandler instances send error messages to disk files, with support for maximum log file sizes and log file rotation.
  4. TimedRotatingFileHandler instances send error messages to disk files, rotating the log file at certain timed intervals.
  5. SocketHandler instances send error messages to TCP/IP sockets.
  6. DatagramHandler instances send error messages to UDP sockets.
  7. SMTPHandler instances send error messages to a designated email address.

最常用的也就是StreamHandler和FileHandler

Configuration

  1. Creating loggers, handlers, and formatters explicitly using Python code that calls the configuration methods listed above.
  2. Creating a logging config file and reading it using the fileConfig() function.
  3. 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相关推荐

  1. Python标准模块--logging

    Python标准模块--logging 参考http://www.cnblogs.com/zhbzz2007/p/5943685.html 1 logging模块简介 logging模块是Python ...

  2. python线程池模块_python并发编程之进程池,线程池,协程(Python标准模块--concurrent.futures(并发未来))...

    需要注意一下 不能无限的开进程,不能无限的开线程 最常用的就是开进程池,开线程池.其中回调函数非常重要 回调函数其实可以作为一种编程思想,谁好了谁就去掉 只要你用并发,就会有锁的问题,但是你不能一直去 ...

  3. Python全栈学习笔记day 40.5+:线程池和线程池的Python标准模块--concurrent.futures

    Python标准模块--concurrent.futures 源码:https://docs.python.org/dev/library/concurrent.futures.html #1 介绍: ...

  4. python日志模块----logging

    使用Python的logging模块能很好的帮我们完成程序的日志功能,其实它跟Java中的log4j有不少相似的地方.下面记录下今天学习到的logging的知识(因为有一些还没真正使用过,不知道是否说 ...

  5. Python日志模块logging高级用法

    推荐图书: <Python程序设计(第3版)>,(ISBN:978-7-302-55083-9),董付国,清华大学出版社,2020年6月第1次印刷,2021年12月第11次印刷,山东省一流 ...

  6. python标准模块string

    python的标准模块string 先看string模块提供什么东东给我们使用: __all__ = ["ascii_letters", "ascii_lowercase ...

  7. Python日志模块logging,这一篇就够了

    ​ 橙好科技logging模块教程 文章目录 1-logging介绍 2-日志作用 3-日志配置basicConfig 3-日志级别level 4-日志格式format 4-输出日志到控制台 5-输出 ...

  8. PYthon常用模块 logging 日志

    一 (简单应用) import logging logging.debug('debug message') logging.info('info message') logging.warning( ...

  9. Python:日志模块logging的应用

    2019独角兽企业重金招聘Python工程师标准>>> 在Python中,上面以实现的和已经实现的,均可以使用logging模块迅速搞定,且仅仅只需要一个配置文件,两行代码,实现过程 ...

最新文章

  1. 关于kafka生产者相关监控指标的理解(未解决)
  2. 处理增删改_这10个批量处理的PPT技巧,让你的效率提升100倍!
  3. aop简介-基于cglib的动态
  4. Microsoft Azure里创建Enterprise Applications
  5. 「野性消费」也不怕!打造供应链数据平台,业务逻辑模板都在这了
  6. php编写计算程序,PHP编写的小应用——计算器
  7. one_code=soup.find('a',href=re.compile(rill)) NameError: name 're' is not defined
  8. Presto架构及原理、安装及部署
  9. ​ java获取中文拼音首字母​
  10. python 在线ide搭建_从头开始制作OJ-在线IDE的搭建
  11. 2018安恒杯11月月赛 MISC
  12. 如何去开发一个webApp
  13. 关于多径效应,平坦衰落,频率选择性衰落以及瑞利衰落的理解
  14. 水库信息化监测系统有哪些?水库信息化监测解决方案
  15. Booth(布斯)算法——补码乘法运算过程
  16. 日语nbsp;五十音图快速记忆法
  17. 使用 ESP32 + Python 实现在线人员入侵检测
  18. 数钱数到手抽筋html5,数钱数到手抽筋的经典句子
  19. html中图片等比例展示,纯 CSS,不用背景,实现图片等比例展示
  20. Java项目:SSH的自动排课系统-遗传算法

热门文章

  1. 12N65-ASEMI高压MOS管12A 650V
  2. 论文阅读方法与技巧【教授经验】
  3. 「常见面试题」Java基础之IO模型连环炮
  4. 电视服务器媒体流中断是什么意思,视频流媒体服务器稳定吗?出现播放中断问题怎么办?...
  5. HTML5 Canvas圆盘抽奖应用DEMO演示
  6. 密码是6-16位字母加数字的正则表达式和验证手机号码的正则表达式
  7. 今日嗅评:搜狗可以搜索微信公众号了,是被腾讯派来探路的吧
  8. 2021新年算法小专题—2.股票买卖利润(Java)
  9. html静态网站基于游戏网站设计与实现共计10个页面 (仿地下城与勇士游戏网页)...
  10. 板式家具生产工艺流程是怎样