Reputation: 6968
I have the following code for creating a logger:
import logging
import a as a
def main():
# create logger
logger = logging.getLogger('cli_logger')
logger.setLevel(logging.DEBUG)
#Create file handler
fh = logging.FileHandler('cli_log.log')
fh.setLevel(logging.DEBUG)
# create console handler
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# create formatter and add it to the handlers
formatter = logging.Formatter('\n%(asctime)s - %(module)s - %(funcName)s()\n%(message)s\n')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)
logger.info("This should print to console and log file!")
logger.debug("This should print to the log file!")
#Do module stuff
a.write_something1()
a.write_something2()
...
if __name__ == '__main__':
main()
Does this mean that - for each function in the module a, I have to get the logger again?
i.e
module a
import logging
def write_something1():
logger = logging.getLogger('cli_logger')
logger.info('Module A1: Console and Debug Log')
logger.debug('Module A1: Debug Log')
def write_something2():
logger = logging.getLogger('cli_logger')
logger.info('Module A2: Console and Debug Log')
logger.debug('Module A2: Debug Log')
Upvotes: 0
Views: 1629
Reputation: 17455
First of all, I would avoid "in-program" configuration of the logger, and move all configuration stuff to an external file as described in http://docs.python.org/2/howto/logging.html#configuring-logging.
Also, in every module I would create a module-wide logger instance specific for that particular module . Thus you'll get a possibility to increase verbosity of a particular module. Also you won't need explicit labels at the beginning of log messages.
Regarding code duplication. Actually it's only one line:
# this is my.library.module
import logging
logger = logging.getLogger("my.library.module")
logger.debug("module loaded")
...
Upvotes: 2