输出日志对于追踪问题比较重要。

默认logger(root)

python使用logging模块来处理日志。通常下面的用法就能满足常规需求:

  1. import logging
  2. logging.debug('some debug level info....')#debug级别消息
  3. logging.info('some info level info...')#info级别消息
  4. logging.warn('some warning level info...')#warning级别消息
  5. logging.critical('some critical level info...')#critical级别消息
  6. logging.error('some error level info...')#error级别消息

输出类似:

  1. [2015-01-07 10:11:34,579](DEBUG)root : adsfaf

即:

[时间](级别)logger名称:消息

默认输出到console。

自定义logger

如果某个模块有个性的需求,比如,记录到文件,或者发送邮件。那么问题来了,怎么破?

如果发生了某种严重的情况,想要发送邮件的话,需要自己定义一个logger,并设置好级别(setLevel(logging.CRITICAL))以及处理器(logging.handlers.SMTPHandler),demo如下:

  1. import logging
  2. logger = logging.getLogger('email_logger')
  3. logger.setLevel(logging.CRITICAL)
  4. mail_handler= logging.handlers.SMTPHandler('your_mail_host_ip','from_addr','to_addr','critical and above level msg from xxx ')
  5.  
  6. logging.info('blablabla...')
  7. logging.error('notice please, an error happens when ...')

记录文件,需要有文件处理器(logging.FileHandler)。demo如下:

  1. import logging
  2. logger = logging.getLogger('file_logger')
  3. logger.addHandler(logging.FileHandler('all.log'))
  4. logger.info('some info...')

还需要其他的handler?参考这里

配置型logger

是否已经厌倦了写代码的方式来自定义logger?好吧,它可以有更多的配置。可以参考这里

三种方式:

1. 上面已经提到了

2. 通过fileConfig读取配置文件

以下来自官方demo

  1. import logging
  2. import logging.config
  3.  
  4. logging.config.fileConfig('logging.conf')
  5.  
  6. # create logger
  7. logger = logging.getLogger('simpleExample')
  8.  
  9. # 'application' code
  10. logger.debug('debug message')
  11. logger.info('info message')
  12. logger.warn('warn message')
  13. logger.error('error message')
  14. logger.critical('critical message')

配置文件:

  1. [loggers]
  2. keys=root,simpleExample
  3.  
  4. [handlers]
  5. keys=consoleHandler
  6.  
  7. [formatters]
  8. keys=simpleFormatter
  9.  
  10. [logger_root]
  11. level=DEBUG
  12. handlers=consoleHandler
  13.  
  14. [logger_simpleExample]
  15. level=DEBUG
  16. handlers=consoleHandler
  17. qualname=simpleExample
  18. propagate=0
  19.  
  20. [handler_consoleHandler]
  21. class=StreamHandler
  22. level=DEBUG
  23. formatter=simpleFormatter
  24. args=(sys.stdout,)
  25.  
  26. [formatter_simpleFormatter]
  27. format=%(asctime)s - %(name)s - %(levelname)s - %(message)s

输出:

  1. $ python simple_logging_config.py
  2. 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
  3. 2005-03-19 15:38:55,979 - simpleExample - INFO - info message
  4. 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
  5. 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
  6. 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message

 

配置文件说明:

声明部分:

  1. [loggers]
  2.  
  3. keys = xxx,xxxx
  4.  
  5. [handlers]
  6.  
  7. keys = xxx,xxx
  8.  
  9. [formatters]
  10.  
  11. keys =xxx,xxx

 

赋值部分

logger赋值

  1. [logger_xxx]
  2. level = DEBUG/INFO/WARN/CRITICAL/ERROR
  3. handlers = [handlers]里定义的handler
  4. qualname = logger
  5. propagate = 1/0 #是否将log丢给上一级处理

  

handler赋值

  1. [handler_xxx]
  2. class = StreamHander/FileHander/handlers.SMTPHandler...
  3. args = 传递给上面class的参数
  4. level = DEBUG/INFO/WARN/CRITICAL/ERROR #是否处理,可以和logger的不同
  5. formatter = [formatters]中定义的格式器

比较有用的一个handlers配置

  1. [handler_rotateFileHandler]
  2. class=handlers.RotatingFileHandler
  3. args=('xxx.log', 'a', 2000000, 9)#日志超过2000000 d的时候,重新另外生成一个文件,保存9天的记录
  4. ...

  

formatter赋值

  1. [formatter_xxx]
  2. format = %(var)s # var:asctime/name/levelname/message/ip/user/module/process/thread...

  

logging.config.fileConfig的特别说明:

disable_existing_loggers是一个可选参数,默认为True。它会阻止在fileConfig语句前面的logger的正常执行。其设计目的是为了反向兼容。

要使得所有的logger都有效,要么在配置文件中,将前面的logger给配置进去。

要么将它改为False。

3. 通过dictConfig读取配置dict

django 就使用了这种方式,配置dict如下:

  1. LOGGING = {
  2. 'version': 1,
  3. 'disable_existing_loggers': True,
  4. 'formatters': {
  5. 'verbose': {
  6. 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
  7. },
  8. 'simple': {
  9. 'format': '%(levelname)s %(message)s'
  10. },
  11. },
  12. 'filters': {
  13. 'special': {
  14. '()': 'project.logging.SpecialFilter',
  15. 'foo': 'bar',
  16. }
  17. },
  18. 'handlers': {
  19. 'null': {
  20. 'level':'DEBUG',
  21. 'class':'django.utils.log.NullHandler',
  22. },
  23. 'console':{
  24. 'level':'DEBUG',
  25. 'class':'logging.StreamHandler',
  26. 'formatter': 'simple'
  27. },
  28. 'mail_admins': {
  29. 'level': 'ERROR',
  30. 'class': 'django.utils.log.AdminEmailHandler',
  31. 'filters': ['special']
  32. }
  33. },
  34. 'loggers': {
  35. 'django': {
  36. 'handlers':['null'],
  37. 'propagate': True,
  38. 'level':'INFO',
  39. },
  40. 'django.request': {
  41. 'handlers': ['mail_admins'],
  42. 'level': 'ERROR',
  43. 'propagate': False,
  44. },
  45. 'myproject.custom': {
  46. 'handlers': ['console', 'mail_admins'],
  47. 'level': 'INFO',
  48. 'filters': ['special']
  49. }
  50. }
  51. }

转载请注明,本文来自Tommy.Yu的博客。谢谢!

python日志浅析的更多相关文章

  1. 浅析python日志重复输出问题

    浅析python日志重复输出问题 问题起源: ​ 在学习了python的函数式编程后,又接触到了logging这样一个强大的日志模块.为了减少重复代码,应该不少同学和我一样便迫不及待的写了一个自己的日 ...

  2. Python日志输出——logging模块

    Python日志输出——logging模块 标签: loggingpythonimportmodulelog4j 2012-03-06 00:18 31605人阅读 评论(8) 收藏 举报 分类: P ...

  3. python日志模块logging

    python日志模块logging   1. 基础用法 python提供了一个标准的日志接口,就是logging模块.日志级别有DEBUG.INFO.WARNING.ERROR.CRITICAL五种( ...

  4. python 日志打印之logging使用介绍

    python 日志打印之logging使用介绍 by:授客QQ:1033553122 测试环境: Python版本:Python 2.7   简单的将日志打印到屏幕 import logging lo ...

  5. python 日志的配置,python对日志封装成类,日志的调用

    # python 日志的配置,python对日志封装成类,日志的调用 import logging # 使用logging模块: class CLog: # --------------------- ...

  6. python日志模块logging学习

    介绍 Python本身带有logging模块,其默认支持直接输出到控制台(屏幕),或者通过配置输出到文件中.同时支持TCP.HTTP.GET/POST.SMTP.Socket等协议,将日志信息发送到网 ...

  7. Python 日志输出中添加上下文信息

    Python日志输出中添加上下文信息 除了传递给日志记录函数的参数(如msg)外,有时候我们还想在日志输出中包含一些额外的上下文信息.比如,在一个网络应用中,可能希望在日志中记录客户端的特定信息,如: ...

  8. python日志模块笔记

    前言 在应用中记录日志是程序开发的重要一环,也是调试的重要工具.但却很容易让人忽略.之前用flask写的一个服务就因为没有处理好日志的问题导致线上的错误难以察觉,修复错误的定位也很困难.最近恰好有时间 ...

  9. Python日志产生器

    Python日志产生器 写在前面 有的时候,可能就是我们做实时数据收集的时候,会有一个头疼的问题就是,你会发现,你可能一下子,没有日志的数据源.所以,我们可以简单使用python脚本来实现产生实时的数 ...

随机推荐

  1. 安装weinre在PC端调试移动端

    1.使用node安装weinre. 2.启动weinre, weinre --httpPort 8081  --boundHost -all- 3.在浏览器打开 http://localhost:80 ...

  2. Euclidean Space

    http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm

  3. Robot Framework--03 案例及资源区

    转自:http://blog.csdn.net/tulituqi/article/details/7585387 这个区域是我们案例结构设计的一个关键区域,这里可以清晰的看到我们整个工程的结构. 还记 ...

  4. winform的扩展的带有截图功能picturebox

    using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using Sys ...

  5. 使用maven编译Java项目 http://www.tuicool.com/articles/YfIfIrq

    使用maven编译Java项目 时间 2014-07-17 17:42:37  Way Lau's Blog 原文  http://www.waylau.com/build-java-project- ...

  6. EF: Raw SQL Queries

    Raw SQL Queries Entity Framework allows you to query using LINQ with your entity classes. However, t ...

  7. Java生成html静态网页

    public static void makeHtml() { try { URL url = new URL("http://www.baidu.com/"); //本实事例通过 ...

  8. XMLBEANS的使用总结

    在本文中,我们将详细了解最好的数据对象XMLBean.从传统角度来说,在Java应用程序中使用XML,就是在从 XML文档向Java导入数据的技术或从数据模型层向XML导出数据技术之间架起了一座桥梁. ...

  9. mysql规范

    1.命名规范 (1)库名.表名.(按现在的规范类似; PromoHayaoRecord),数据库名使用小写,字段名必须使用小写字母,并采用下划线分割.(2)库名.表名.字段名禁止超过32个字符.(3) ...

  10. select2

    .select2-container .select2-choice { height: 34px; line-height: 34px; } .自定义 组件高度 在css 里面设置 .select2 ...