16:使用日志收集应用程序信息

使用标准的python日志记录从Web应用程序捕获调试和错误输出。

背景

了解我们的Web应用程序中发生了什么是很重要的。在开发中,我们可能需要收集一些输出。在生产中,当其他人使用该站点时,我们可能需要检测问题。我们需要 Logging .

幸运的是,Pyramid使用普通的python方法进行日志记录。在您的 development.ini 有许多行可以将日志配置为某些合理的默认值。然后,您会看到Pyramid发送的消息,例如,当一个新的请求出现时。

目标

  • 检查用于日志记录的配置设置。

  • 将日志语句添加到视图代码中。

步骤

  1. 首先我们复制 view_classes 步骤:

    cd ..; cp -r view_classes logging; cd logging
    $VENV/bin/pip install -e .
    
  2. 延伸 logging/tutorial/views.py 要记录消息:

     1import logging
     2log = logging.getLogger(__name__)
     3
     4from pyramid.view import (
     5    view_config,
     6    view_defaults
     7    )
     8
     9
    10@view_defaults(renderer='home.pt')
    11class TutorialViews:
    12    def __init__(self, request):
    13        self.request = request
    14
    15    @view_config(route_name='home')
    16    def home(self):
    17        log.debug('In home view')
    18        return {'name': 'Home View'}
    19
    20    @view_config(route_name='hello')
    21    def hello(self):
    22        log.debug('In hello view')
    23        return {'name': 'Hello View'}
    
  3. 最后让我们编辑 development.ini 启用Pyramid应用程序日志记录的配置文件:

    [app:main]
    use = egg:tutorial
    pyramid.reload_templates = true
    pyramid.includes =
        pyramid_debugtoolbar
    
    [server:main]
    use = egg:waitress#main
    listen = localhost:6543
    
    # Begin logging configuration
    
    [loggers]
    keys = root, tutorial
    
    [logger_tutorial]
    level = DEBUG
    handlers =
    qualname = tutorial
    
    [handlers]
    keys = console
    
    [formatters]
    keys = generic
    
    [logger_root]
    level = INFO
    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
    
  4. 确保测试仍然通过:

    $VENV/bin/pytest tutorial/tests.py -q
    ....
    4 passed in 0.41 seconds
    
  5. 运行 Pyramid 应用程序时使用:

    $VENV/bin/pserve development.ini --reload
    
  6. 在浏览器中打开http://localhost:6543/和http://localhost:6543/howdy。注意,在控制台和调试工具栏中,您记录的消息。

分析

在我们的配置文件中 development.ini 我们的 tutorial python包被设置为记录器,并配置为在 DEBUG 或更高级别。当您访问http://localhost:6543时,您的控制台现在将显示:

2013-08-09 10:42:42,968 DEBUG [tutorial.views][MainThread] In home view

此外,如果您已将Pyramid应用程序配置为使用 pyramid_debugtoolbar ,其中一个菜单中显示日志记录语句。

参见

也见 登录 .