欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

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

发布时间:2025/3/8 55 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Python牛刀小试(五)--logging模块 小编觉得挺不错的,现在分享给大家,帮大家做个参考.
由于想给自己的Python程序添加日志功能,学习下Python的日志模块。

一个简单的例子:

点击(此处)折叠或打开

  • import logging

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

    点击(此处)折叠或打开

  • D:\stock>python test4_logger.py
  • 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 ----------------------------------------简单的日志的分割线-----------------------------------------------------------
    由于自己写的模块,需要模块化,要有配置文件,能复用。控制台和文件都能输出。
    源代码如下:

    配置文件如下:

    点击(此处)折叠或打开

  • [loggers]
  • keys=root,simpleExample
  • [handlers]
  • keys=consoleHandler,fileHandler
  • [formatters]
  • keys=simpleFormatter
  • [logger_root]
  • level=DEBUG
  • handlers=consoleHandler,fileHandler
  • [logger_simpleExample]
  • level=DEBUG
  • handlers=consoleHandler,fileHandler
  • qualname=simpleExample
  • propagate=0
  • [handler_consoleHandler]
  • class=StreamHandler
  • level=DEBUG
  • formatter=simpleFormatter
  • args=(sys.stdout,)
  • [formatter_simpleFormatter]
  • format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
  • datefmt=
  • [handler_fileHandler]
  • class=logging.handlers.TimedRotatingFileHandler
  • level=DEBUG
  • formatter=simpleFormatter
  • args=("zsd.log", "midnight")

  • Python执行文件:

    点击(此处)折叠或打开

  • import logging
  • import logging.config

  • logging.config.fileConfig('logging.conf')
  • # create logger
  • logger = logging.getLogger('simpleExample')

  • # 'application' code
  • logger.debug('debug message')
  • logger.info('info message')
  • logger.warn('warn message')
  • logger.error('error message')
  • logger.critical('critical message')


  • 总结

    以上是生活随笔为你收集整理的Python牛刀小试(五)--logging模块的全部内容,希望文章能够帮你解决所遇到的问题。

    如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。