Python Pyramid 简明教程

Python Pyramid - Logging

为了收集有关应用程序的有用信息,Pyramid 使用 Python 标准库中的 logging 模块。它在开发和生产模式中均可用于检测应用程序运行期间是否存在问题。应用程序日志可以包括您自己的消息和来自第三方模块的消息。

In order to collect useful information about the application, Pyramid uses the logging module from Python’s standard library. It proves useful in development as well as production mode to detect problems if any, during the running of the application. The application log can include your own messages integrated with messages from third-party modules.

已记录的消息具有以下预定义类型(按严重性递减排列)−

The logged messages have following predefined types (in the order of decreasing severity) −

  1. CRITICAL

  2. ERROR

  3. WARNING

  4. INFO

  5. DEBUG

  6. NOTSET

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

By default, he logging messages are redirected to sys.stderr stream. To start collecting logging messages, we need to declare a Logger object.

import logging
log = logging.getLogger(__name__)

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

Log messages can now be generated with logger methods corresponding to the desired logging levels. To generate a message which can prove useful for debugging the application, use log.debug() message with appropriate message string.

基于 PasteDeploy 配置的 Pyramid 应用程序使得启用并入日志记录支持非常容易。PasteDeploy 文件(development.ini 和 production.ini)使用 ConfigParser 格式,该格式用于日志记录模块的配置参数中。当 pserve 命令调用 development.ini 中与日志记录相关的部分时,它们会传递到日志记录模块的配置流程中。

A Pyramid application based on PasteDeploy configuration makes it very easy to enable incorporate logging support. The PasteDEploy files (development.ini as well as production.ini) use the ConfigParser format used in the logging module’s configuration parameters. The logging related sections in development.ini are passed to the logging module’s configuration process when it is invoked by pserve command.

配置文件中的各种 logger 部分为应用程序对象指定了键、格式和日志记录级别。

Various logger sections in the configuration file specify the keys, formats and the logger levels for the application objects.

以下日志记录相关部分在典型的“development.ini”文件中声明 −

Following logging related sections are declared in a typical "development.ini" file −

# 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 文件中。

Let us add these sections in the development.ini file of our Hello application in the previous chapter.

Example

接下来,声明 Logger 对象并在 hello_world() few 函数中放置调试消息。以下是 init.py 代码 −

Next, declare the Logger object and put a debug message in the hello_world() few function. Here’s the init.py code −

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 模板-

The hello_world() view renders the following hello.html template −

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

像往常一样运行该应用程序-

Run the application as usual −

pserve development.ini

http://localhost:6543/Tutorialpoint URL 输入到浏览器中时,命令窗口会回显以下调试消息-

When http://localhost:6543/Tutorialpoint URL is entered in the browser, the command window echoes following debug message −

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

Output

因为已在配置中启用了调试工具栏,所以它显示在浏览器中-

Since the debug toolbar is enabled in the configuration, it is displayed in the browser −

hello tp

调试消息还显示在调试工具栏的日志选项卡中,如下所示-

The debug message is also displayed on the logging tab of the debug toolbar as shown below −

log msgs