How to log messages _only once_ from all modules ?

Terry Reedy tjreedy at udel.edu
Wed Nov 25 15:03:50 EST 2009


Jean-Michel Pichavant wrote:

> 
> 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.

I have never used logging, but if and when I have a need for it, the 
advice above and your clear example will be a good guide to getting 
started. Thank you from me too.

tjr

> [server.py]
> 
> 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 ')
> 
> 
> [client.py]
> 
> 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()
>    rootLogger.addHandler(logging.FileHandler("client.log"))
>    rootLogger.handlers[-1].setFormatter(logging.Formatter("%(asctime)s 
> %(name)-12s %(levelname)-8s %(message)s"))
>    rootLogger.setLevel(logging.DEBUG)
>    ser = Server()
>    cli = Client()
>    ser.util()
>    cli.client_test()
> 
> Happy logging,
> 
> Jean-Michel




More information about the Python-list mailing list