Today I decide to signup for a free trial of the newrelic monitoring agent and I wanted to write on how to setup the agent on a Pylons app.
EDIT: Commenter Graham Dumpleton has advised against this setup in the comments. There’s the potential risk of the agent initializing twice and additional modules not working correctly. So please don’t use this setup on a production app.
Open the middleware.py file located on PRJNAME/config and add the following. Make sure to set the correct path where your newrelic.ini file is located
#import the agent import newrelic.agent #create a middleware class to initialize the agent class NewRelicAgent(object): def __init__(self, app): self.app = app newrelic.agent.initialize('/path/to/the/file/newrelic.ini') @newrelic.agent.wsgi_application() def __call__(self, environ, start_response): return self.app(environ, start_response)
Now it’s time to add our custom middleware inside the make_app def
# CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares) app = NewRelicAgent(app)
And that’s it. Now it’s time to collect some stats :).
3 thoughts on “Setup The Newrelic Monitoring Agent On A Pylons App”
I wouldn’t recommend using a middleware like that such that the constructor of the middleware does the initialisation of the New Relic Python agent.
There are two reasons for that.
The first is that the Python agent will raise an exception if initialize() is called twice with different arguments. I know you hardwire the argument and so it will be the same, but still probably not good to encourage the possibility that it could be called twice.
The second is that the instrumentation which is added to some Python modules will not work if agent initialisation is performed after the module is first imported. In other words, to guarantee best chance that things will work as intended, the agent initialisation should be done before all module imports for things that are to be instrument. So, should be done as early as possible in process startup, and deferring it to middleware creation doesn’t allow that.
I tried to take an approach like the one you mention of initializing the agent before all the modules but I ended up with errors most notably with the psycopg2 driver. I agree is not ideal, so far the app I’m monitoring has been running without a problem. I’ll investigate further, for now I’ll add a warning to the post. Thanks!.