日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

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

發布時間:2025/3/8 python 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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模块的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。