如何为金字塔/挂架2编写日志记录中间件?

时间:2011-02-08 17:54:01

标签: python logging mongodb pyramid

我想使用mongodb或redis来保存金字塔/挂架中的用户日志,但无法找到有关创建middeware的文档。我该怎么做呢?

4 个答案:

答案 0 :(得分:9)

标准中间件

class LoggerMiddleware(object):
    '''WSGI middleware'''

    def __init__(self, application):

        self.app = application

    def __call__(self, environ, start_response):

        # write logs

        try:
            return self.app(environ, start_response)
        except Exception, e:
            # write logs
            pass
        finally:
            # write logs
            pass

在金字塔中创建应用代码:

from paste.httpserver import serve
from pyramid.response import Response
from pyramid.view import view_config

@view_config()
def hello(request):
    return Response('Hello')

if __name__ == '__main__':
    from pyramid.config import Configurator
    config = Configurator()
    config.scan()
    app = config.make_wsgi_app()

    # Put middleware
    app = LoggerMiddleware(app)

    serve(app, host='0.0.0.0')

答案 1 :(得分:2)

找不到任何文档是完全奇怪的,因为日志记录模块的Python文档非常详细和完整:

http://docs.python.org/library/logging.html#handler-objects

您需要实现自己的MongoDBHandler并使用MongoDB附加emit()方法 通过pymongo。

答案 2 :(得分:1)

在这种情况下的另一个选择是根本不使用中间件,只需在金字塔中使用BeforeRequest事件。

from pyramid.events import NewRequest
import logging

def mylogger(event):
    request = event.request
    logging.info('request occurred')

config.add_subscriber(mylogger, NewRequest)

答案 3 :(得分:0)

万一有人偶然发现,您可以使用充当中间件的Tween。 您可以将日志记录放入 call 方法。

class simple_tween_factory(object):
def __init__(self, handler, registry):
    self.handler = handler
    self.registry = registry

    # one-time configuration code goes here

def __call__(self, request):
    # code to be executed for each request before
    # the actual application code goes here

    response = self.handler(request)

    # code to be executed for each request after
    # the actual application code goes here

    return response

https://docs.pylonsproject.org/projects/pyramid/en/latest/narr/hooks.html#registering-tweens