Python Forum

Full Version: Properly share logger objects
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi
In python file 1 I have

 
      def main():
       
           logger = logging.getLogger("pre-commit-logger")
           handler = logging.FileHandler(log_file)
           logger.addHandler(handler)
           logger.warning("logger warn")
           .......
The warning message is correctly added to the log file

In file 2 I have

 
   logger = logging.getLogger("pre-commit-logger")

   logger.warning("executing asdasdasdasdasdasdasdas!!!")
When I execute the script I get

   No handlers could be found for logger "pre-commit-logger"

I have obviously misunderstood something and qwould be grateful of an expanation

Thanks
How are these files related? Could you provide complete code that reproduces the issue?
(Jun-26-2017, 10:07 AM)CardBoy Wrote: [ -> ]Hi
In python file 1 I have

 
      def main():
       
           logger = logging.getLogger("pre-commit-logger")
           handler = logging.FileHandler(log_file)
           logger.addHandler(handler)
           logger.warning("logger warn")
           .......
The warning message is correctly added to the log file

In file 2 I have

 
   logger = logging.getLogger("pre-commit-logger")

   logger.warning("executing asdasdasdasdasdasdasdas!!!")
When I execute the script I get

   No handlers could be found for logger "pre-commit-logger"

I have obviously misunderstood something and qwould be grateful of an expanation

Thanks

You may be assuming that like in Java, the logger is a singleton and that you don't need to add the handler to the second instance. But it's easy to check if the two references are the same object or not. In a sane world, the handlers are defined in a logger configuration file anyway.