Python 有没有办法忽略日志文件中的输出并在控制台上打印

Python 有没有办法忽略日志文件中的输出并在控制台上打印,python,logging,Python,Logging,我正在使用python日志模块 有没有办法忽略日志文件中的输出,但在控制台上打印 我尝试了logger.propagate=False和logger.StreamHandler(stream=None),但没有帮助这可以通过更改为 例如: import logging import sys def function(): logger = logging.getLogger('function') logger.info("This is test messsage from logg

我正在使用python日志模块

有没有办法忽略日志文件中的输出,但在控制台上打印


我尝试了
logger.propagate=False
logger.StreamHandler(stream=None)
,但没有帮助

这可以通过更改为

例如:

import logging
import sys

def function():
  logger = logging.getLogger('function')
  logger.info("This is test messsage from logger.")

if __name__ == '__main__':
  main = logging.getLogger()
  main.setLevel(logging.DEBUG)

  fmt = logging.Formatter('%(asctime)s  -  %(name)s  -  %(levelname)s  -  %(message)s')
  handle = logging.StreamHandler(sys.stdout)
  handle.setFormatter(fmt)
  main.addHandler(handle)

  function()

# output on console
# 2020-01-27 08:21:08,211  -  function  -  INFO  -  This is test messsage from logger.

将上述配置添加到main方法会将所有记录器输出重定向到控制台。

下面的示例说明了最简单的方法。不向文件写入任何内容,并将输出发送到控制台(
sys.stderr
)。关键是
basicConfig()
调用;对于这个例子,其他的一切都只是说明性的

import logging

logger = logging.getLogger(__name__)

def main():
    logger.debug('DEBUG message')
    logger.info('INFO message')
    logger.warning('WARNING message')
    logger.error('ERROR message')
    logger.critical('CRITICAL message')

if __name__ == '__main__':
    # use whatever level and format you need
    logging.basicConfig(level=logging.INFO, format='%(message)s')
    main()
当运行时,这个会打印

INFO message    
WARNING message 
ERROR message   
CRITICAL message
应更新问题,以包括所需行为、特定问题或错误,以及重现问题所需的最短代码。