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

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

问题描述

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

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:

  • 很容易查看记录调用的地点和时间(甚至是哪一行).
  • 您可以同时登录到文件、套接字等几乎所有内容.
  • 您可以根据严重性区分您的日志记录.

Print 没有这些.

Print doesn't have any of these.

此外,如果您的项目打算由其他 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中,为什么使用日志而不是打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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