在python中,为什么要使用日志记录而不是print? [英] In python, why use logging instead of print?

查看:257
本文介绍了在python中,为什么要使用日志记录而不是print?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于复杂项目中的简单调试,是否有理由使用python记录器而不是print?那其他用例呢?是否每个都有一个公认的最佳用例(尤其是在您仅查找标准输出时)?

For simple debugging in a complex project is there a reason to use the python logger instead of print? What about other use-cases? Is there an accepted best use-case for each (especially when you're only looking for stdout)?

我一直都听说这是最佳实践",但我一直无法弄清原因.

I've always heard that this is a "best practice" but I haven't been able to figure out why.

推荐答案

日志记录程序包具有许多有用的功能:

The logging package has a lot of useful features:

  • 轻松查看从何处以及何时(甚至是哪行)进行日志记录调用.
  • 您可以同时登录文件,套接字,几乎所有内容.
  • 您可以根据严重性来区分日志记录.

打印没有这些.

此外,如果您的项目打算由其他python工具导入,则对于您的包来说,将内容打印到stdout是不好的做法,因为用户可能不知道打印消息的来源.使用日志记录,包的用户可以选择是否要通过您的工具传播日志记录消息.

Also, if your project is meant to be imported by other python tools, it's bad practice for your package to print things to stdout, since the user likely won't know where the print messages are coming from. With logging, users of your package can choose whether or not they want to propogate logging messages from your tool or not.

这篇关于在python中,为什么要使用日志记录而不是print?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆