How to log messages _only once_ from all modules ?

Jean-Michel Pichavant jeanmichel at
Wed Nov 25 12:58:21 CET 2009

Barak, Ron wrote:
> Hi,
> I'm trying to add the logging module to my application, but I seem to 
> be missing something.
> My application (a wxPython one) has a main script that calls various 
> helper classes.
> I want the log messages from all modules to go to one central log file.
> When I implement logging, I think that due to preparation, I get the 
> same message more than once.
> Here's an example:
> [snip example]
> Could you suggest what should I change in the above scripts so that 
> the log messages would appear only once ?
> Thanks,
> Ron.
If you are starting with the logging facility, I would suggest to add 
handlers only to the root logger (in your __main__ section).

Basically, never configure or add handlers to any logger except for the 
root logger in your __main__ section. There are very few reasons why you 
would break this rule. And when you'll be familiar with the logging 
module you'll when to break it.


import logging
import logging.handlers

logger = logging.getLogger(__name__) # you'd better to create the logger 
at the module level, you may want to log within   the module function

def aFunction(a, b, ,c):
    logger.debug('You called aFunction')

class Server():
    def __init__(self):
        self.logger = logger

    def util(self):
        self.logger.warning('This message comes from Server module ')


import logging
import logging.handlers
from server import Server

logger = logging.getLogger(__name__)

class Client():
    def __init__(self):
        self.logger = logger

    def client_test(self):
        self.logger.warning("This message comes from Client module")

if __name__ == "__main__":
    rootLogger = logging.getLogger()
%(name)-12s %(levelname)-8s %(message)s"))
    ser = Server()
    cli = Client()

Happy logging,


More information about the Python-list mailing list