我相信使用Python的内置日志记录模块logger
将主模块中的root记录器作为根记录器时,这是标准做法。假设这是正确的,在我看来,对于可能作为主模块运行或可能不作为主模块运行的任何模块,我都需要明确检查。原因是,如果我遵循标准的调用方法,logging.getLogger(__name__)
则会得到一个名为logger__main__
而不是root logger的记录器:
import logging
print logging.getLogger().name # root
print logging.getLogger(__name__).name # __main__
最佳实践是否总是值得检查?
if __name__ == "__main__":
logger = logging.getLogger()
else:
logger = logging.getLogger(__name__)
这并不是很糟糕,因为我总是会有其他仅在if时才运行的代码__name__ == "__main__"
(通常包括对的调用logging.basicConfig
),但是只需要一行而不是更多行会很好。
如高级记录教程中所述,使用的实践logging.getLogger(__name__)
是针对模块级记录器的。
在脚本(或应用程序的主模块)中,我通常根本不创建记录器,但是我确实更改了根记录器的配置。
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 to 'warning')")
opts.add_argument("files", metavar='file', nargs='*',
help="one or more files to process")
args = opts.parse_args(argv)
logging.basicConfig(level=getattr(logging, args.log.upper(), None),
format='%(levelname)s: %(message)s')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句