我试图找出在多个模块中使用python登录的最佳实践。我在这里看到:http://docs.python.org/2/howto/logging#logging-from-multiple-modules关于如何使用根记录器来记录多个模块。正如链接指出的那样,你无法分辨你的消息来自哪里,因为它们都显示了名称“root”。
在我看来有两种选择(这假设我的模块不在包结构中,但只是同一文件夹中的一堆模块):
1)使用示例中的根记录器,但更改日志格式以包含文件名:
# myapp.py
import logging
import mylib
def main():
logging.basicConfig(format='%(asctime)s %(filename)s %(levelname)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO) #filename='myapp.log',
logging.info('Started')
mylib.do_something()
logging.info('Finished')
if __name__ == '__main__':
main()
#mylib.py
import logging
def do_something():
logging.info('Do something')
In [4]: import myapp
In [5]: myapp.main()
03/06/2014 12:22:07 PM myapp.py INFO: Started
03/06/2014 12:22:07 PM mylib.py INFO: Do something
03/06/2014 12:22:07 PM myapp.py INFO: Finished
2)在主应用程序中使用根记录器,但在子模块中使用命名记录器,并在日志格式中使用“name”而不是“filename”:
# myapp.py
import logging
import mylib
def main():
#logging.basicConfig(format='%(asctime)s %(filename)s %(levelname)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO) #filename='myapp.log',
logging.basicConfig(format='%(asctime)s %(name)s %(levelname)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO) #filename='myapp.log',
logging.info('Started')
mylib.do_something()
logging.info('Finished')
if __name__ == '__main__':
main()
#mylib.py
import logging
def do_something():
#logging.info('Do something')
logger = logging.getLogger(__name__)
logger.info('Do something')
In [3]: import myapp
In [4]: myapp.main()
03/06/2014 12:27:29 PM root INFO: Started
03/06/2014 12:27:29 PM mylib INFO: Do something
03/06/2014 12:27:29 PM root INFO: Finished
答案 0 :(得分:9)
Vinay Sajip(日志记录模块的维护者)创建一个类似于你的选项#2的recommendation here,除了你可以在任何地方使用一个命名的记录器,即使在myapp中:
import logging
import mylib
logger = logging.getLogger(__name__)
def main():
logging.basicConfig(format='%(asctime)s %(module)s %(levelname)s: %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO)
logger.info('Started')
mylib.do_something()
logger.info('Finished')
if __name__ == '__main__':
main()
产生
03/06/2014 12:59:25 PM myapp INFO: Started
03/06/2014 12:59:25 PM mylib INFO: Do something
03/06/2014 12:59:25 PM myapp INFO: Finished
请注意,如果您使用的是%(module)s
而不是%(name)s
,那么在获得myapp
或root
或{{1}之前,您会获得myapp.py
}。
这种对称 - 总是使用__main__
- 如果logger
有时被称为脚本并且有时作为模块导入,则可能特别有用。