[Tutor] Logger object not passed between modules

Peter Otten __peter__ at web.de
Tue Jul 26 13:40:03 CEST 2011


Luke Thomas Mergner wrote:

> I am very new to Python and programming, basically just a curious
> hobbyist.  I am building a learning app that hopefully will include a
> wxPython GUI.  Right now I am trying to understand my code better by
> including print statements.  Now I know that I could just print to the
> terminal, but I thought 'why not try this nice little logger class.'  And
> it works perfectly in the main class App(wx.App), but I can't seem to pass
> the same logger object to the imported modules.  I'm verifying this by
> printing the logger object to terminal (stdout?).  I've spent close to 6
> hours trying to figure this out, and I need some help.
> 
> The logger object is created within a function in the main app class.  Is
> this wrong? I thought that logger ensured the same object is used by both
> classes.  The logger.getLogger(__name__) doesn't set anything other than
> the name used to describe the source of the message, so how do I make sure
> I'm using the same log object?  

No, the name is used to identify a logger; different names mean different 
loggers.

> I assume the problem is either scope (the
> log has to be in the module, not the class) or passing the object
> properly, neither of which I"m very comfortable with obviously.

Loggers are put into a hierarchy similar to a directory tree with the root 
logger at the top. By default the other loggers pass logging messages up to 
their parent so that all messages (or LogRecords) are eventually seen by the 
root logger. In most cases it is sufficient to handle them there, and the 
easiest way to add a suitable formatter and handler is 
logging.basicConfig():

>>> import logging
>>> class App:
...     def __init__(self):
...             self.logger = logging.getLogger("main")
...
>>> class Frame:
...     def __init__(self):
...             self.logger = logging.getLogger("frame")
...
>>> logging.basicConfig(level=logging.DEBUG, filename="tmp.log")
>>> app = App()
>>> frame = Frame()
>>> frame.logger.info("hello from frame")
>>> app.logger.info("hello from app")
>>> with open("tmp.log") as f: print f.read()
...
INFO:frame:hello from frame
INFO:main:hello from app




More information about the Tutor mailing list