【发布时间】:2023-04-09 04:37:01
【问题描述】:
我想使用 mongodb 或 redis 为金字塔/塔架中的用户保留日志,但找不到有关创建中间件的文档。我该怎么办?
【问题讨论】:
标签: python logging mongodb pyramid
我想使用 mongodb 或 redis 为金字塔/塔架中的用户保留日志,但找不到有关创建中间件的文档。我该怎么办?
【问题讨论】:
标签: python logging mongodb pyramid
在这种情况下,另一个选择是根本不使用中间件,而只是在金字塔中使用 BeforeRequest 事件。
from pyramid.events import NewRequest
import logging
def mylogger(event):
request = event.request
logging.info('request occurred')
config.add_subscriber(mylogger, NewRequest)
【讨论】:
如果有人偶然发现这一点,您可以使用 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
【讨论】:
标准中间件
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')
【讨论】:
找不到任何文档非常奇怪,因为日志记录模块的 Python 文档非常冗长且完整:
http://docs.python.org/library/logging.html#handler-objects
您需要实现自己的 MongoDBHandler 并将 emit() 方法附加到 MongoDB 通过 pymongo。
【讨论】: