Logging

Peter Otten __peter__ at web.de
Tue Mar 4 16:30:51 CET 2014


Igor Korot wrote:

> Hi, ALL,
> Could someone please explain to me how the code in
> http://docs.python.org/2/howto/logging#logging-from-multiple-modules
> works?
> In particular I'm interested in how the mylib.py knows about the
> myapp.log.
> 
> What I mean is: logging object is not passed to mylib.py, so
> essentially it should create a new instance of the logging object.
> 
> What am I missing?

loggers are cached and organized in a tree. If you ask for a logger

abc = logging.getLogger("a.b.c")

you get the same logger every time. At the top of the tree there is the root 
logger

>>> import logging
>>> root = logging.getLogger()
>>> abc = logging.getLogger("a.b.c")
>>> ab = logging.getLogger("a.b")
>>> a = logging.getLogger("a")
>>> abc.parent is ab
True
>>> ab.parent is a
True
>>> a.parent is root
True
>>> logging.getLogger("a.b.c") is abc
True
>>> 


logging.info(...) 

is basically a shortcut for

root.info(...)

that also does a basicConfig() if necessary.

By default loggers delegate handling log messages to their parent. You only 
have to tell the root logger what to do with the incoming messages.

There are optimizations (placeholders for the intermediate loggers), but the 
above is the basic concept.

> But this question comes from the following fact about my application.
> I tried to create a logging object which will store the logging
> information to the file in the main class. Then I pass this object to
> another class constructor and use it in that second class.
> 
> Upon running everything is OK, but when the program successfully
> finishes, the log file has 0 length.
> 
> AFAIU, I'm doing it properly and the example referenced is wrong, yet
> the results are completely different.
> 
> Thank you for any expplanation.

Did you run the example consisting of myapp.py and myapp.lib? Did it work? 
If so, what did you differently in your real app?

Please provide a minimal example showing the unexpected behaviour.




More information about the Python-list mailing list