如何为 Pyramid/Pylons 2 编写日志中间件?

5 投票
4 回答
3997 浏览
提问于 2025-04-16 11:27

我想在pyramid/pylons中使用mongodb或redis来保存用户的日志,但找不到关于如何创建中间件的文档。我该怎么做呢?

4 个回答

2

找不到任何文档真是太奇怪了,因为Python的日志模块文档其实写得很详细、很完整:

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

你需要自己实现一个MongoDBHandler,并通过pymongo把emit()方法连接到MongoDB上。

2

在这种情况下,另一个选择是根本不使用中间件,而是直接在Pyramid框架中使用一个叫做BeforeRequest的事件。

from pyramid.events import NewRequest
import logging

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

config.add_subscriber(mylogger, NewRequest)
10

标准中间件

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

在Pyramid框架中创建应用程序的代码:

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')

撰写回答