简体   繁体   English

为什么 Python 日志记录默认写入标准错误?

[英]Why Python logging writes to stderr by default?

Related to Does Python logging write to stdout or stderr by default?默认情况下 Python 日志是否写入标准输出或标准错误有关? but I want to know WHY it defaults to stderr instead WHAT is the default.但我想知道为什么它默认为stderr而不是默认值是什么

For me it isn't really obvious why stderr is the default.对我来说,为什么stderr是默认值并不是很明显。 I noticed that something is wrong when I run python script.py | tee out.log我注意到当我运行python script.py | tee out.log时出现问题python script.py | tee out.log and ended up with empty log file. python script.py | tee out.log并以空日志文件结束。 Now I know that It can be solved by either python script.py 2>&1 | tee out.log现在我知道它可以通过python script.py 2>&1 | tee out.log python script.py 2>&1 | tee out.log or using stream parameter: python script.py 2>&1 | tee out.log或使用stream参数:

logging.basicConfig(stream=sys.stdout)

After that event it seems reasonable to me to change default stream to stdout in each script to avoid being surprised again.在那次事件之后,我认为在每个脚本中将默认stream更改为stdout以避免再次感到惊讶似乎是合理的。 Is that a good practice?这是一个好习惯吗? Will I miss something?我会错过什么吗?

You probably don't want to change the default to stdout.您可能不想将默认值更改为标准输出。 The reason for that is stderr is meant to be an output for all messages that are just some internal and/or debugging program information like logs and errors, rather than actual output, the result of the program.原因是 stderr 意味着 output 用于所有消息,这些消息只是一些内部和/或调试程序信息,如日志和错误,而不是实际的 output,程序的结果。

A computer program basically takes data as input and create data as output.计算机程序基本上将数据作为输入并创建数据为 output。 While a program is running, one may be informed of its actions thanks to a monitoring, without altering its output data.在程序运行时,可以通过监视通知其操作,而无需更改其 output 数据。 To do so, computer programs traditionally have two outputs, one standard output for data and another one for monitoring (logging and errors): stderr.为此,计算机程序通常有两个输出,一个用于数据的标准 output,另一个用于监控(记录和错误):stderr。

This is especially useful when your program is pipeable: you wouldn't have error messages in-between video pixels, for example, because it would break your data.这在您的程序可管道化时特别有用:例如,您不会在视频像素之间出现错误消息,因为它会破坏您的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM