Search code examples
pythonloggingmongodbpyramid

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 find the doc on creating a middeware. How do I go about it?


Solution

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