i noticed when call function can still access logger though wasn’t passed. example, following file writes testlogger.log:
import logging datetime import datetime def printhello(): print('hello') logger.info('printed hello') printgoodbye() def printgoodbye(): print('goodbye') logger.info('printed goodbye') if __name__ == "__main__": logger = logging.getlogger(__name__) format = '%(name)s - %(levelname)s - %(message)s' logging.basicconfig(filename='testlogger.log', level=logging.debug, format=format) logger.info(datetime.now().strftime('%h:%m %d-%m-%y.log')) logger.info('about call function printhello') printhello() logger.info('now exiting') is how should done? also, project i’m working on divided several modules, which, when completed, call each other. should there separate log file each module? if so, convention name log file after script created it?
the best way follow advice python logging documentation:
the logger name hierarchy analogous python package hierarchy, , identical if organise loggers on per-module basis using recommended construction
logging.getlogger(__name__). that’s because in module,__name__module’s name in python package namespace.
doing give relatively fine-grained control on logging. default (using logging.basicconfig), logging each module work same way: @ same level , go same place, if want can turn logging on or off specific modules, or turn logging high level 1 module. see python logging multiple handlers, @ different log levels? example of how that.
the reason logger variable accessible across functions because when assign @ top-level, "global" variable created (it's not global, has module scope). better way explicitly create logger @ top of script:
import logging datetime import datetime logger = logging.getlogger(__name__) def printhello(): print('hello') logger.info('printed hello') printgoodbye() def printgoodbye(): print('goodbye') logger.info('printed goodbye') if __name__ == "__main__": format = '%(name)s - %(levelname)s - %(message)s' logging.basicconfig(filename='testlogger.log', level=logging.debug, format=format) logger.info(datetime.now().strftime('%h:%m %d-%m-%y.log')) logger.info('about call function printhello') printhello() logger.info('now exiting')
Comments
Post a Comment