Logging from files doesn't work

Peter Otten __peter__ at web.de
Thu Oct 12 04:20:53 EDT 2017


Andrew Z wrote:

> Hello,
> 
>  apparently my reading comprehension is nose diving these days. After
> reading python cookbook and a few other tutorials i still can't get a
> simple logging from a few files to work.
> I suspected my file organization - all files are in the same directory,
> causing problem. But it appears it is not.
> 
> Anyway, in the example below, only logging from main.py works. I also want
> to have login from "test1/test.py" to write into the same common log file.
> 
> And how can i accomplish the same if test.py is in the same directory as
> main.py?
> 
> dir structure:
> src/
>      |- main.py
>      |-test/

Shouldn't that be 

       |-test1/

?

>              |-test.py
> 
> code:
> test.py:
> 
> import logging
> # neither of below produce any results
> 
> log = logging.getLogger("test1.test")
> # log = logging.getLogger(__name__)
> 
> def fun():
>    print("DADADA")
>    log.debug(" DADADADA " )
> 
> 
> main.py:
> 
> from test1.test import fun
> 
> def main():
> 
>    log = logging.getLogger(__name__)
>    log.setLevel(logging.DEBUG)
> 
>    fh = logging.FileHandler("nja_" +
> datetime.now().strftime("%Y_%b_%d_%H_%M_%S") +".log")
>    formatter = logging.Formatter('%(levelname)s - %(asctime)s -
> %(funcName)10s() %(lineno)s - %(message)s')
>    fh.setFormatter(formatter)
>    log.addHandler(fh)
> 
>    log.debug("Yes, this line is in the log file")
> 
>    fun()
> 
>    log.debug("And this one is too")

You have already worked out why the names are what they are.
You can avoid the problem if you attach the handler to the root logger, e. 
g.

def main():
    root_log = logging.getLogger()
    root_log.setLevel(logging.DEBUG)

    fh = logging.FileHandler(
        "nja_" + datetime.now().strftime("%Y_%b_%d_%H_%M_%S") +".log"
    )
    formatter = logging.Formatter(
        '%(levelname)s - %(asctime)s - %(funcName)10s()'
        '%(lineno)s - %(message)s'
    )
    fh.setFormatter(formatter)
    root_log.addHandler(fh)

    log = logging.getLogger(__name__)

    log.debug("Yes, this line is in the log file")

    fun()

    log.debug("And this one is too")
"And this one is too")

That way you can capture messages from the whole hierarchy regardless of its 
actual layout.




More information about the Python-list mailing list