為了收集關(guān)于應(yīng)用程序的有用信息,Pyramid使用Python標(biāo)準(zhǔn)庫中的 日志 模塊。在開發(fā)和生產(chǎn)模式中,它被證明是有用的,可以在應(yīng)用程序的運行過程中發(fā)現(xiàn)問題。應(yīng)用程序的日志可以包括你自己的信息和第三方模塊的信息。
記錄的消息有以下預(yù)定義類型(按照嚴(yán)重程度遞減的順序)?
默認(rèn)情況下,他的日志信息被重定向到sys.stderr流。為了開始收集日志信息,我們需要聲明一個Logger對象。
import logging
log = logging.getLogger(__name__)
現(xiàn)在可以用與所需的日志級別相對應(yīng)的日志方法來生成日志信息。要生成對調(diào)試應(yīng)用程序有用的消息,可以使用 log.debug() 消息和適當(dāng)?shù)南⒆址?/p>
基于PasteDeploy配置的Pyramid應(yīng)用程序可以非常容易地啟用合并日志支持。PasteDEploy文件(development.ini以及production.ini)在日志模塊的配置參數(shù)中使用了 ConfigParser 格式。開發(fā).ini中的日志相關(guān)部分在pserve命令調(diào)用時被傳遞給日志模塊的配置過程。
配置文件中的各種日志部分指定了應(yīng)用程序?qū)ο蟮逆I、格式和日志級別。
以下是典型的 “development.ini “文件中聲明的與日志相關(guān)的部分
# 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應(yīng)用程序的 development.ini 文件中添加這些部分。
接下來,聲明Logger對象,并在 hello_world() 的少數(shù)函數(shù)中放入調(diào)試信息。下面是 __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>
像往常一樣運行應(yīng)用程序-
pserve development.ini
當(dāng)在瀏覽器中輸入 http://localhost:6543/Tutorialpoint URL 時,命令窗口呼出以下調(diào)試信息—-。
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
由于在配置中啟用了調(diào)試工具欄,它將在瀏覽器中顯示—-。
調(diào)試信息也顯示在調(diào)試工具欄的日志選項卡上,如下圖所示。
更多建議: