linkdd
linkdd

Reputation: 1052

Global variables lost in Bottle route

I'm using Bottle as Python web framework.

Basically, here is what I am doing :

auth.py :

from bottle import get

logger = None
webserver = None

def load(server):
    global logger, webserver

    logger = server.getLogger('auth')
    webserver = server

@get('/auth')
def auth():
    logger.debug('Entering route')

webserver.py :

import bottle
import imp

class WebServer(object):
    # ...

    def getLogger(self, name):
        # ...

    def start_wsgi(self):
        # ...

        app = bottle.default_app()

        mod = imp.load_source('auth', 'auth.py')
        mod.load(self)

        # ...

        return app

    # ...

ws = WebServer()
app = ws.start_wsgi()

NB: no error handling or extra code here, I just exposed what is interesting to the issue (in my opinion)

It seems that the global scope is not shared between the main process (which runs the WebServer code) and the thread handling the request (logger is still None when I hit the /auth URL).

By printing id(logger) in function load() and route auth() (with a global logger added, just to be sure), I get two different ids.

How can I share my loggers to the threads handling the request ?

PS: I tried adding a field to the default Bottle application, like this :

app = default_app()
app.logger = # mylogger

And then in the route :

app = default_app()
app.logger.debug('Message')

But it seems that even the default_app() is different.

Upvotes: 0

Views: 1666

Answers (1)

ron rothman
ron rothman

Reputation: 18128

How can I share my loggers to the threads handling the request ?

...

By printing id(logger) in function load() and route auth() (with a global logger added, just to be sure), I get two different ids.

That's okay--your logger variables need not reference the same logger object for things to work properly across threads.

Each thread should just acquire its logger:

logger = logging.getLogger('foo.bar.baz')

That will work just fine. (Across threads, mind you, not across processes.)

Btw, I'm not sure what your Webserver.getLogger function returns, but in any case this function seems unnecessary.

P.S., Just curious--Are you actually seeing a problem with your logging output, or were you just surprised when you observed that the ids of the different logger variables were not identical?

Upvotes: 1

Related Questions