Tuesday 5 January 2016

Python: Disable console logging


By default, log messages are sent to console. Observe following example.
import logging
import logging.handlers

#Define logger
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s')

LOG_FILENAME="/Users/harikrishna_gurram/temp.log"
#Define handler to write to standard output
handler = logging.FileHandler(LOG_FILENAME)

formatter = logging.Formatter('[%(levelname)s] %(message)s')
handler.setFormatter(formatter)
handler.setLevel(logging.DEBUG)

#Adding handler to logger
logger.addHandler(handler)

def logMessages():
    logger.debug("Debug message")
    logger.info("Information Message")
    logger.warn("Warning Message")
    logger.error("Error Message")
    logger.critical("Critical Message")

if(__name__=="__main__"):
    logMessages()


Run above program, you will get following log messages to console.
2015-10-23 11:32:53,153 __main__     DEBUG    Debug message
2015-10-23 11:32:53,153 __main__     INFO     Information Message
2015-10-23 11:32:53,153 __main__     WARNING  Warning Message
2015-10-23 11:32:53,153 __main__     ERROR    Error Message
2015-10-23 11:32:53,153 __main__     CRITICAL Critical Message


By setting propagate field to False, you can disable this feature. Add following statement to above program and rerun.
logger.propagate = False
import logging
import logging.handlers

#Define logger
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s')

LOG_FILENAME="temp.log"
#Define handler to write to standard output
handler = logging.FileHandler(LOG_FILENAME)

formatter = logging.Formatter('[%(levelname)s] %(message)s')
handler.setFormatter(formatter)
handler.setLevel(logging.DEBUG)

#Adding handler to logger
logger.addHandler(handler)
logger.propagate=False

def logMessages():
    logger.debug("Debug message")
    logger.info("Information Message")
    logger.warn("Warning Message")
    logger.error("Error Message")
    logger.critical("Critical Message")

if(__name__=="__main__"):
    logMessages()


Run above program, you won’t see any log messages in console.




Previous                                                 Next                                                 Home

No comments:

Post a Comment