為了收集關于應用程序的有用信息,Pyramid使用Python標準庫中的 日志 模塊。在開發(fā)和生產模式中,它被證明是有用的,可以在應用程序的運行過程中發(fā)現問題。應用程序的日志可以包括你自己的信息和第三方模塊的信息。
記錄的消息有以下預定義類型(按照嚴重程度遞減的順序)?
默認情況下,他的日志信息被重定向到sys.stderr流。為了開始收集日志信息,我們需要聲明一個Logger對象。
import logging
log = logging.getLogger(__name__)
現在可以用與所需的日志級別相對應的日志方法來生成日志信息。要生成對調試應用程序有用的消息,可以使用 log.debug() 消息和適當的消息字符串。
基于PasteDeploy配置的Pyramid應用程序可以非常容易地啟用合并日志支持。PasteDEploy文件(development.ini以及production.ini)在日志模塊的配置參數中使用了 ConfigParser 格式。開發(fā).ini中的日志相關部分在pserve命令調用時被傳遞給日志模塊的配置過程。
配置文件中的各種日志部分指定了應用程序對象的鍵、格式和日志級別。
以下是典型的 “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
當在瀏覽器中輸入 http://localhost: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
由于在配置中啟用了調試工具欄,它將在瀏覽器中顯示—-。
調試信息也顯示在調試工具欄的日志選項卡上,如下圖所示。
更多建議: