我知道这个问题现在在 StackOverflow 中被问了两次,但还没人回答这个问题。
这是我的代码:
logging.basicConfig(filename="logfile.log", filemode='w',
format='%(asctime)s:%(levelname)s:%(message)s', datefmt='%m/%d/%Y %H:%M:%S')
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical error message')
输出控制台是空。只有 logfile.log 具有日志字符串。但是当我删除文件名属性时,它开始显示控制台。我想在控制台中显示并写入我的日志文件。我想念什么?请用代码回答。我已经阅读了文档两三次了。谢谢。
最佳答案
只需获取记录器的句柄并添加 StreamHandler 和 FileHandler
import logging
logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s")
logger = logging.getLogger()
fileHandler = logging.FileHandler("{0}/{1}.log".format(logPath, fileName))
fileHandler.setFormatter(logFormatter)
logger.addHandler(fileHandler)
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
logger.addHandler(consoleHandler)
关于Python 3.7 日志记录问题未显示在输出中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54887126/