Logging from files doesn't work
Andrew Z wrote:
> 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
> dir structure:
> |- main.py
Shouldn't that be
> import logging
> # neither of below produce any results
> log = logging.getLogger("test1.test")
> # log = logging.getLogger(__name__)
> def fun():
> log.debug(" DADADADA " )
> from test1.test import fun
> def main():
> log = logging.getLogger(__name__)
> 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')
> log.debug("Yes, this line is in the log file")
> 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.
root_log = logging.getLogger()
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'
log = logging.getLogger(__name__)
log.debug("Yes, this line is in the log file")
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