我想使用 mongodb 或 redis 为金字塔/塔中的用户保留日志,但找不到有关创建中间件的文档。我该怎么做?
问问题
3366 次
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')
于 2011-02-09T06:34:35.383 回答
2
找不到任何文档是完全奇怪的,因为日志记录模块的 Python 文档非常冗长和完整:
http://docs.python.org/library/logging.html#handler-objects
您需要实现自己的 MongoDBHandler 并通过 pymongo 将 emit() 方法附加到 MongoDB。
于 2011-02-08T18:01:28.050 回答
2
在这种情况下,另一个选择是根本不使用中间件,而只是在金字塔中使用 BeforeRequest 事件。
from pyramid.events import NewRequest
import logging
def mylogger(event):
request = event.request
logging.info('request occurred')
config.add_subscriber(mylogger, NewRequest)
于 2011-02-09T17:42:48.937 回答
1
如果有人偶然发现这一点,您可以使用充当中间件的 Tween。您可以将日志记录放在调用方法中。
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
于 2019-10-16T02:55:24.537 回答