How do I write a logging middleware for pyramid/pylons 2?
I want to use either mongodb or redis to keep logs for users in pyramid/pylons, but cant开发者_如何学Python find the doc on creating a middeware. How do I go about it?
Standart middleware
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
In pyramid creating app code:
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')
Can not find any docs is completely weird since the Python documentation of the logging module is pretty verbose and complete:
http://docs.python.org/library/logging.html#handler-objects
You need to implement your own MongoDBHandler and attach the emit() method with MongoDB through pymongo.
Another option in this case would be to not use middleware at all and simply use a BeforeRequest event in pyramid.
from pyramid.events import NewRequest
import logging
def mylogger(event):
    request = event.request
    logging.info('request occurred')
config.add_subscriber(mylogger, NewRequest)
In case anybody stumbles upon this, you can use the Tween that acts as a middleware. You can put the logging in the call method.
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
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论