Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 574
Timmy Avatar asked Feb 08 '11 17:02

Timmy


4 Answers

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')
like image 84
estin Avatar answered Nov 07 '22 20:11

estin


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.

like image 27
Andreas Jung Avatar answered Nov 07 '22 20:11

Andreas Jung


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)
like image 28
Rocky Burt Avatar answered Nov 07 '22 21:11

Rocky Burt


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

like image 29
RickSore Avatar answered Nov 07 '22 21:11

RickSore