Python牛刀小试(五)--logging模块

由于想给自己的Python程序添加日志功能,学习下Python的日志模块。

一个简单的例子:

点击(此处)折叠或打开

  1. import logging

  2. ##第一个简单的例子
  3. logging.warning('Watch out!') # will print a message to the console 输出到控制台
  4. logging.info('I told you so') # will not print anything 没有任何输出信息
输出至控制台的信息,如下:

点击(此处)折叠或打开

  1. D:\stock>python test4_logger.py
  2. WARNING:root:Watch out!
输出日志到文件中

点击(此处)折叠或打开

import logging

##输出到example日志文件中
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
在当前目录中,有一个example.log日志文件,输出日志如下:

点击(此处)折叠或打开

DEBUG:root:This message should go to the log file INFO:root:So should this WARNING:root:And this, too
----------------------------------------简单的日志的分割线-----------------------------------------------------------
由于自己写的模块,需要模块化,要有配置文件,能复用。控制台和文件都能输出。
源代码如下:

配置文件如下:

点击(此处)折叠或打开

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

Python执行文件:

点击(此处)折叠或打开

  1. import logging
  2. import logging.config

  3. logging.config.fileConfig('logging.conf')
  4. # create logger
  5. logger = logging.getLogger('simpleExample')

  6. # 'application' code
  7. logger.debug('debug message')
  8. logger.info('info message')
  9. logger.warn('warn message')
  10. logger.error('error message')
  11. logger.critical('critical message')


你可能感兴趣的:(Python牛刀小试(五)--logging模块)