简体   繁体   English

如何将python logging.debug()消息输出到标准输出?

[英]How can I get python logging.debug() messages to output to standard output?

I have a script that gives me messages through the python logging module: logging.debug("a message here") . 我有一个脚本通过python日志模块给我消息: logging.debug("a message here") Yet when I run the linux command python3 myscript.py -v >> log.txt I get a blank file. 然而,当我运行linux命令python3 myscript.py -v >> log.txt我得到一个空白文件。 How can I get the debug messages to output to the log file? 如何将调试消息输出到日志文件?

By default, the logging module logs to sys.stderr . 默认情况下, logging模块会记录到sys.stderr Capture stream 2, stderr instead: 捕获流2,而不是stderr

python3 myscript.py -v 2>> log.txt

You can also redirect both stdin and stderr to the same file: 您还可以将stdinstderr重定向到同一个文件:

python3 myscript.py -v >> log.txt 2>&1

Here stderr is sent to the same output stdin (output 1) is directed to. 这里stderr被发送到同一输出stdin (输出1)被定向到。

This is assuming you already set the logging level to allow for level DEBUG messages. 假设您已将日志记录级别设置为允许级别DEBUG消息。

Last but not least, you can tell logging.basicConfig() to log to a different stream instead of stderr : 最后但并非最不重要的是,您可以告诉logging.basicConfig()记录到不同的流而不是stderr

logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)

or you can give it a filename, that way no redirection is needed: 或者您可以给它一个文件名,这样就不需要重定向:

logging.basicConfig(filename='log.txt', level=logging.DEBUG)

Set your log level to be on debug. 将日志级别设置为调试。

Logger.setLevel(Logger.DEBUG)

See the docs for logging wherein they state: 查看他们声明的日志记录文档:

Sets the threshold for this logger to lvl. 将此记录器的阈值设置为lvl。 Logging messages which are less severe than lvl will be ignored. 记录不如lvl严重的消息将被忽略。 When a logger is created, the level is set to NOTSET (which causes all messages to be processed when the logger is the root logger, or delegation to the parent when the logger is a non-root logger). 创建记录器时,级别设置为NOTSET(当记录器是根记录器时会导致处理所有消息,或者当记录器是非root记录器时委托给父级)。 Note that the root logger is created with level WARNING. 请注意,根记录器是使用级别WARNING创建的。

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

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