user6882757
user6882757

Reputation:

Is there any way to ignore the output in the log file and print on the console

I am using python logging module

Is there any way to ignore the output in the log file but print on the console?

i tried logger.propagate = False and logger.StreamHandler(stream=None) but could not help

Upvotes: 2

Views: 688

Answers (2)

Vinay Sajip
Vinay Sajip

Reputation: 99297

The easiest way is illustrated with the following example. Nothing is written to file, and output is sent to the console (sys.stderr). The key thing is the basicConfig() call; everything else is just illustrative for this example.

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()

When run, this prints

INFO message    
WARNING message 
ERROR message   
CRITICAL message

Upvotes: 0

Vivek Mehta
Vivek Mehta

Reputation: 2642

This can be done by changing Stream Handler to sys.stdout

Example:

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.

Adding above configuration to your main method will redirect all logger output to console.

Upvotes: 3

Related Questions