简体   繁体   English

防止 Python 记录器打印到控制台

[英]Prevent Python logger from printing to console

I'm getting mad at the logging module from Python, because I really have no idea anymore why the logger is printing out the logging messages to the console (on the DEBUG level, even though I set my FileHandler to INFO).我对来自 Python 的日志记录模块很生气,因为我真的不知道为什么记录器将日志消息打印到控制台(在 DEBUG 级别,即使我将 FileHandler 设置为 INFO)。 The log file is produced correctly.日志文件已正确生成。 But I don't want any logger information on the console.但我不想在控制台上显示任何记录器信息。 Here is my configuration for the logger:这是我对记录器的配置:

template_name = "testing"
fh = logging.FileHandler(filename="testing.log")
fr = logging.Formatter("%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s")
fh.setFormatter(fr)
fh.setLevel(logging.INFO)
logger = logging.getLogger(template_name)
# logger.propagate = False # this helps nothing
logger.addHandler(fh)

Would be nice if anybody could help me out:)如果有人能帮助我,那就太好了:)

I found this question as I encountered a similar issue, after I had removed the logging.basicConfig() .我在删除logging.basicConfig()后遇到类似问题时发现了这个问题。 It started printing all logs in the console.它开始在控制台中打印所有日志。

In my case, I needed to change the filename on every run, to save a log file to different directories.在我的例子中,我需要在每次运行时更改文件名,以将日志文件保存到不同的目录。 Adding the basic config on top (even if the initial filename is never used, solved the issue for me. (I can't explain why, sorry).在顶部添加基本配置(即使从未使用过初始文件名,也为我解决了这个问题。(我无法解释原因,抱歉)。

What helped me was adding the basic configuration in the beginning:帮助我的是在开始时添加基本配置:

logging.basicConfig(filename=filename,
                        format='%(levelname)s - %(asctime)s - %(name)s - %(message)s',
                        filemode='w',
                        level=logging.INFO)

Then changing the filename by adding a handler in each run:然后通过在每次运行中添加处理程序来更改文件名:

file_handler = logging.FileHandler(path_log + f'/log_run_{c_run}.log')
formatter    = logging.Formatter('%(asctime)s : %(levelname)s : %(name)s : %(message)s')
file_handler.setFormatter(formatter)
logger_TS.addHandler(file_handler)

Also curious side-note.也很好奇旁注。 If I don't set the formater ( file_handler.setFormatter(formatter) ) before setting the handler with the new filename, the initially formated logging (levelname, time, etc.) is missing in the log files.如果我在使用新文件名设置处理程序之前没有设置格式化程序 ( file_handler.setFormatter(formatter) ),则日志文件中缺少最初格式化的日志记录(级别名称、时间等)。

So, the key is to set the logging.basicConfig before, then set the add the handler.所以,关键是先设置logging.basicConfig,然后再设置add handler。 As @StressedBoi69420 indicated above.如上文所述@StressedBoi69420。

Hope that helps a bit.希望那些对你有帮助。

You should be able to add a StreamHandler to handle stdout and set the handlers log level to a level above 50. (Standard log levels are 50 and below.)您应该能够添加StreamHandler来处理标准输出并将处理程序日志级别设置为高于 50 的级别。(标准日志级别为 50 及以下。)

Example of how I'd do it...我将如何做的例子......

import logging
import sys

console_log_level = 100

logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s",
                    filename="testing.log",
                    filemode="w")
console = logging.StreamHandler(sys.stdout)
console.setLevel(console_log_level)
root_logger = logging.getLogger("")
root_logger.addHandler(console)

logging.debug("debug log message")
logging.info("info log message")
logging.warning("warning log message")
logging.error("error log message")
logging.critical("critical log message")

Contents of testing.log... testing.log 的内容...

2019-11-21 12:53:02,426,426 root INFO info log message
2019-11-21 12:53:02,426,426 root WARNING warning log message
2019-11-21 12:53:02,426,426 root ERROR error log message
2019-11-21 12:53:02,426,426 root CRITICAL critical log message

Note: The only reason I have the console_log_level variable is because I pulled most of this code from a default function that I use that will set the console log level based on an argument value.注意:我拥有console_log_level变量的唯一原因是因为我从默认的 function 中提取了大部分代码,我使用它将根据参数值设置控制台日志级别。 That way if I want to make the script "quiet", I can change the log level based on a command line arg to the script.这样,如果我想让脚本“安静”,我可以根据脚本的命令行参数更改日志级别。

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

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