logging - Do I need to explicitly check for __name__ == "__main__" before calling getLogger in Python? -
i believe it's standard practice when using python's built-in logging module have logger
in main module root logger. assuming correct, seems me module may or may not run main need explicitly check. reason if follow standard practice of calling logging.getlogger(__name__)
i'll logger named __main__
rather root logger:
import logging print logging.getlogger().name # root print logging.getlogger(__name__).name # __main__
is best practice check?
if __name__ == "__main__": logger = logging.getlogger() else: logger = logging.getlogger(__name__)
this not bad because i'll have other code runs if __name__ == "__main__"
(often including call logging.basicconfig
) nice need 1 line instead of more.
the practice of using logging.getlogger(__name__)
meant module-level logger, explained in advanced logging tutorial.
in script (or main module of application) don't create logger @ all, change configuration of root logger;
opts = argparse.argumentparser(prog='foo', description=__doc__) group.add_argument('-v', '--version', action='version', version=__version__) opts.add_argument('--log', default='warning', choices=['debug', 'info', 'warning', 'error'], help="logging level (defaults 'warning')") opts.add_argument("files", metavar='file', nargs='*', help="one or more files process") args = opts.parse_args(argv) logging.basicconfig(level=getattr(logging, args.log.upper(), none), format='%(levelname)s: %(message)s')
Comments
Post a Comment