日志模块.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. # -*- coding: UTF-8 -*-
  2. import logging
  3. # logging.info('老弟,来了') # 不打印,info级别
  4. # logging.warning('来错地方来') # 输出屏幕,警告级别
  5. logging.basicConfig(filename='myapp.log',level=logging.INFO)
  6. logging.info('info msg')
  7. logging.warning('WR msg')
  8. logging.debug('DUG msg')
  9. #======================= 示例 =========================#
  10. # -*- encoding:utf-8 -*-
  11. import logging
  12. # create logger
  13. logger_name = "example"
  14. logger = logging.getLogger(logger_name)
  15. logger.setLevel(logging.DEBUG)
  16. # create file handler
  17. log_path = "./log.log"
  18. fh = logging.FileHandler(log_path)
  19. fh.setLevel(logging.WARN)
  20. # create formatter
  21. fmt = "%(asctime)-15s %(levelname)s %(filename)s %(lineno)d %(process)d %(message)s"
  22. datefmt = "%a %d %b %Y %H:%M:%S"
  23. formatter = logging.Formatter(fmt, datefmt)
  24. # add handler and formatter to logger
  25. fh.setFormatter(formatter)
  26. logger.addHandler(fh)
  27. # print log info
  28. logger.debug('debug message')
  29. logger.info('info message')
  30. logger.warn('warn message')
  31. logger.error('error message')
  32. logger.critical('critical message')
  33. """
  34. ##### 文件配置
  35. 配置文件logging.conf如下:
  36. ```[loggers]
  37. keys=root,example01
  38. [logger_root]
  39. level=DEBUG
  40. handlers=hand01,hand02
  41. [logger_example01]
  42. handlers=hand01,hand02
  43. qualname=example01
  44. propagate=0
  45. [handlers]
  46. keys=hand01,hand02
  47. [handler_hand01]
  48. class=StreamHandler
  49. level=INFO
  50. formatter=form02
  51. args=(sys.stderr,)
  52. [handler_hand02]
  53. class=FileHandler
  54. level=DEBUG
  55. formatter=form01
  56. args=('log.log', 'a')
  57. [formatters]
  58. keys=form01,form02
  59. [formatter_form01]
  60. format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s```
  61. 使用程序logger.py如下:
  62. ```#!/usr/bin/python
  63. # -*- encoding:utf-8 -*-
  64. import logging
  65. import logging.config
  66. logging.config.fileConfig("./logging.conf")
  67. # create logger
  68. logger_name = "example"
  69. logger = logging.getLogger(logger_name)
  70. logger.debug('debug message')
  71. logger.info('info message')
  72. logger.warn('warn message')
  73. logger.error('error message')
  74. logger.critical('critical message')
  75. """
  76. ##### 字典配置
  77. # 有兴趣的童靴可以使用```logging.config.dictConfig(config)```编写一个示例程序发给我,以提供给我进行完善本文。
  78. ##### 监听配置
  79. # 有兴趣的童靴可以使用```logging.config.listen(port=DEFAULT_LOGGING_CONFIG_PORT)```编写一个示例程序发给我,以提供给我进行完善本文。
  80. # 更多详细内容参考[logging.config日志配置](http://python.usyiyi.cn/python_278/library/logging.config.html#module-logging.config)