[Python-de] Fragge zu logging

Georg Brandl g.brandl at gmx.net
Fr Jul 20 10:51:52 CEST 2007


Bastian Venthur schrieb:
> Hi Liste,
> 
> ich hab hier ein komisches Problem mit loggern. Um es zu demonstrieren
> hier ein minimales Beispiel:
> 
> === main.py ===
> 
> import logging
> import module1
> 
> if __name__ == "__main__":
>     logging.basicConfig(level=logging.DEBUG, format="%(name)-12s
> %(levelname)-8s %(message)s")
>     logger = logging.getLogger()
>     logger.info("Logger initialized")
> 
>     module1.foo()
> 
> === module1.py ===
> 
> import logging
> 
> logger = logging.getLogger("module1")
> logger.debug("Logger initialized")
> 
> def foo():
>     logger.debug("Entered foo()")
> 
> === Ausgabe von python main.py ===
> root         INFO     Logger initialized
> module1      DEBUG    Entered foo()
> 
> 
> Meine Frage: Warum wurde logger.debug("Logger initialized") in
> module1.py nicht ausgeführt? Ein print an der Stelle würde etwas ausgeben.
> 
> Das ist nur die minimale Varianbe meines Prolbems. Ich habe in einem
> Projekt in jedem Modul auf Modulebene einen Logger (sie heißen alle
> "logger"). Manchmal muss auf Modulebene aber außerhalb von Funktionen
> etwas geloggt werden, und entweder kommt gar nichts oder z.B. innerhalb
> eines try/exept Blockes auf Modulebene auch gerne mal eine Fehlermeldung
> "No handlers could be found for logger foo". Innerhalb von Funktionen
> dagegen gibt es keine Probleme.
> 
> Irgendwie versteh ich das nicht, kann mir jemand auf die Sprünge helfen?

Deine modulweiten Statements in module1 werden ausgeführt, *bevor*
logging.basicConfig von main.py aufgerufen wird. Deshalb verhält sich
logger.debug() falsch. (Ersetzt du es mit .error(), bekommst du die
angesprochene Fehlermeldung).

Die Lösung ist also, logging.basicConfig() vor dem Import von module1
aufzurufen, oder entsprechendes.

Georg


-- 
Thus spake the Lord: Thou shalt indent with four spaces. No more, no less.
Four shall be the number of spaces thou shalt indent, and the number of thy
indenting shall be four. Eight shalt thou not indent, nor either indent thou
two, excepting that thou then proceed to four. Tabs are right out.





Mehr Informationen über die Mailingliste python-de