Pyramid 日志

2023-03-30 17:58 更新

为了收集关于应用程序的有用信息,Pyramid使用Python标准库中的 日志 模块。在开发和生产模式中,它被证明是有用的,可以在应用程序的运行过程中发现问题。应用程序的日志可以包括你自己的信息和第三方模块的信息。

记录的消息有以下预定义类型(按照严重程度递减的顺序)−

  • CRITICAL
  • ERROR
  • WARNING
  • INFO
  • DEBUG
  • NOTSET

默认情况下,他的日志信息被重定向到sys.stderr流。为了开始收集日志信息,我们需要声明一个Logger对象。

import logging
log = logging.getLogger(__name__)

现在可以用与所需的日志级别相对应的日志方法来生成日志信息。要生成对调试应用程序有用的消息,可以使用 log.debug() 消息和适当的消息字符串。

基于PasteDeploy配置的Pyramid应用程序可以非常容易地启用合并日志支持。PasteDEploy文件(development.ini以及production.ini)在日志模块的配置参数中使用了 ConfigParser 格式。开发.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

输出

由于在配置中启用了调试工具栏,它将在浏览器中显示—-。

Python Pyramid - 日志

调试信息也显示在调试工具栏的日志选项卡上,如下图所示。

Python Pyramid - 日志


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号