在 python 中,我可以将日志写入控制台,但它没有写入文件

In python I can write a log to console but its not getting written into file

import logging 
#Create and configure logger 
logging.basicConfig(filename="newfile.txt", format='%(asctime)s %(message)s',filemode='w') 
logging.debug("Harmless debug Message") 
logging.info("Just an information") 
logging.warning("Its a Warning") 
logging.error("Did you try to divide by zero") 
logging.critical("Internet is down") 

在控制台中打印所有这些信息。它从未写入文件。真的很感谢那些帮助我解决这个问题的人。从早上开始在互联网上搜索尝试了所有的可能性,但日志仍然没有写入文件

我从日志文档中得到这个例子

import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s',
                    filename='myapp.log',
                    filemode='w')
logging.debug('A debug message')
logging.info('Some information')
logging.warning('A shot across the bows')

以及我在网上看到的示例,它们都在创建 .log 文件。所以尝试将文件的扩展名从 txt 更改为 log

使用所需的流和文件处理程序创建一个新记录器:

import logger, sys
logger = logging.Logger('AmazeballsLogger')
#Stream/console output
logger.handler = logging.StreamHandler(sys.stdout)
logger.handler.setLevel(logging.WARNING)
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
logger.handler.setFormatter(formatter)
logger.addHandler(self.handler)
#File output
fh = logging.FileHandler("test.log")
fh.setLevel(logging.DEBUG)
fh.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
logger.addHandler(fh)

你已经准备好试一试了:

print(logger.handlers)

logger.critical("critical")
logger.error("error")
logger.warning("warning")
logger.info("info")
logger.debug("debug")

以下控制台输出仅显示警告及更高级别:

[<StreamHandler stdout (WARNING)>, <FileHandler C:\Users\...\test.log (DEBUG)>]
2020-04-13 17:52:57,729 - CRITICAL - critical
2020-04-13 17:52:57,731 - ERROR - error
2020-04-13 17:52:57,734 - WARNING - warning

虽然 test.log 包含所有级别:

2020-04-13 17:52:57,729 - AmazeballsLogger - CRITICAL - critical
2020-04-13 17:52:57,731 - AmazeballsLogger - ERROR - error
2020-04-13 17:52:57,734 - AmazeballsLogger - WARNING - warning
2020-04-13 17:52:57,736 - AmazeballsLogger - INFO - info
2020-04-13 17:52:57,736 - AmazeballsLogger - DEBUG - debug

关键是要了解 logging handlers work and checking whether they use correct levels (as in the code cells above, just print logger.handlers). Furthermore, overwriting basic configuration is a bad practice that can lead to problems when you run multiple loggers in the same python environment. I recommend this video,它阐明了 python 日志记录中的 stream/file 处理程序。