【问题标题】:How do I write a logging middleware for pyramid/pylons 2?如何为金字塔/塔架 2 编写日志中间件?
【发布时间】:2023-04-09 04:37:01
【问题描述】:

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

【问题讨论】:

    标签: python logging mongodb pyramid


    【解决方案1】:

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

    from pyramid.events import NewRequest
    import logging
    
    def mylogger(event):
        request = event.request
        logging.info('request occurred')
    
    config.add_subscriber(mylogger, NewRequest)
    

    【讨论】:

    • 请求后有事件吗?我想记录,但不延迟响应
    • 有 pyramid.events.NewResponse 但如果未创建响应,例如在引发未捕获的异常时,它不会触发。
    【解决方案2】:

    如果有人偶然发现这一点,您可以使用 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

    【讨论】:

      【解决方案3】:

      标准中间件

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

      【讨论】:

      • 我可以将其设置为在响应之后发生,以便尽快将数据发送给用户吗?
      【解决方案4】:

      找不到任何文档非常奇怪,因为日志记录模块的 Python 文档非常冗长且完整:

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

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

      【讨论】:

      • 是的,我并不太担心日志记录部分,而是想弄清楚将金字塔放在哪里
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-23
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 2019-09-14
      • 2017-06-13
      • 1970-01-01
      相关资源
      最近更新 更多