Python Pyramid - 日誌記錄



為了收集關於應用程式的有用資訊,Pyramid 使用 Python 標準庫中的logging模組。它在開發和生產模式中都非常有用,可以檢測應用程式執行期間出現的任何問題。應用程式日誌可以包含您自己的訊息以及來自第三方模組的訊息。

已記錄的訊息具有以下預定義型別(按嚴重性遞減順序):

  • CRITICAL(嚴重錯誤)
  • ERROR(錯誤)
  • WARNING(警告)
  • INFO(資訊)
  • DEBUG(除錯)
  • NOTSET(未設定)

預設情況下,日誌訊息會重定向到 sys.stderr 流。要開始收集日誌訊息,我們需要宣告一個 Logger 物件。

import logging
log = logging.getLogger(__name__)

現在可以使用與所需日誌級別對應的 logger 方法生成日誌訊息。要生成對除錯應用程式有用的訊息,請使用帶有相應訊息字串的log.debug()訊息。

基於 PasteDeploy 配置的 Pyramid 應用程式使得啟用日誌支援變得非常容易。PasteDeploy 檔案(development.ini 和 production.ini)使用 logging 模組配置引數中使用的ConfigParser格式。當 pserve 命令呼叫時,development.ini 中與日誌相關的部分會被傳遞到 logging 模組的配置過程。

配置檔案中的各種 logger 部分指定了應用程式物件的鍵、格式和 logger 級別。

典型的 "development.ini" 檔案中聲明瞭以下與日誌相關的部分:

# Begin logging configuration
[loggers]
keys = root, hello
[logger_hello]
level = DEBUG
handlers =
qualname = hello
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]

#level = INFO
level=DEBUG
handlers = console
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s

# End logging configuration

讓我們將這些部分新增到上一章中 Hello 應用程式的development.ini檔案中。

示例

接下來,宣告 Logger 物件並在hello_world()函式中新增一條除錯訊息。這是__init__.py程式碼:

from pyramid.config import Configurator
from pyramid.response import Response
from pyramid.view import view_config
import logging

log = logging.getLogger(__name__)

from pyramid.renderers import render_to_response

def hello_world(request):
   log.debug('In hello view')
   return render_to_response('templates/hello.html',
{'name':request.matchdict['name']},request=request)

def main(global_config, **settings):
   config = Configurator(settings=settings)
   config.include('pyramid_jinja2')
   config.add_jinja2_renderer(".html")
   config.add_route('hello', '/{name}')
   config.add_view(hello_world, route_name='hello')
   return config.make_wsgi_app()

hello_world() 檢視呈現以下 hello.html 模板:

<html>
   <body>
      <h1>Hello, {{ name }}!</h1>
   </body>
</html>

像往常一樣執行應用程式:

pserve development.ini

當在瀏覽器中輸入https://:6543/Tutorialpoint URL 時,命令視窗會回顯以下除錯訊息:

Starting monitor for PID 11176.
Starting server in PID 8472.
2022-06-26 01:22:47,032 INFO [waitress][MainThread] Serving on http://[::1]:6543
2022-06-26 01:22:47,032 INFO [waitress][MainThread] Serving on http://127.0.0.1:6543
2022-06-26 01:22:47,418 DEBUG [hello][waitress-1] In hello view

輸出

由於在配置中啟用了除錯工具欄,它會顯示在瀏覽器中:

Hello TP

除錯訊息也會顯示在除錯工具欄的日誌選項卡上,如下所示:

Log Msgs
廣告