我如何编写金字塔/塔2的日志记录中间件?

问题描述 投票:4回答:4

我想使用mongodb或redis将用户的日志保存在金字塔/塔中,但是找不到有关创建中间软件的文档。我该怎么办?

python logging mongodb pyramid
4个回答
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')

2
投票

由于日志记录模块的Python文档非常冗长和完整,因此找不到任何文档是完全奇怪的:

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

您需要实现自己的MongoDBHandler并在MongoDB上附加generate()方法通过pymongo。


1
投票

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

from pyramid.events import NewRequest
import logging

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

config.add_subscriber(mylogger, NewRequest)

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

© www.soinside.com 2019 - 2024. All rights reserved.