By using
Stream handler, you can send log records to a stream. Following program defines
a stream handler that writes log records to standard output.
import logging import sys #Define logger logger = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s') #Define handler to write to standard output handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter('[%(levelname)s] %(message)s') handler.setFormatter(formatter) handler.setLevel(logging.WARN) #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 output.
2015-10-23 10:19:12,176 __main__ DEBUG Debug message [WARNING] Warning Message [ERROR] Error Message 2015-10-23 10:19:12,176 __main__ INFO Information Message [CRITICAL] Critical Message 2015-10-23 10:19:12,177 __main__ WARNING Warning Message 2015-10-23 10:19:12,177 __main__ ERROR Error Message 2015-10-23 10:19:12,177 __main__ CRITICAL Critical Message
We set the
log level WARN to the handler, so handler only logs Warning, Error, Critical
messages.
StreamHandler
provides following methods.
Method
|
Description
|
emit(record)
|
If
formatter is specified, it is used to format the record.
|
flush()
|
Flush the
stream.
|
No comments:
Post a Comment