ImportLoggingImportSYSclassConsolehandler (logging. Handler): Terminator='\ n' def __init__(Self, level=logging. NOTSET): Super ().__init__(level)def_flush (self, Stream): Self.acquire ()Try: ifStream andHasattr (Stream,'Flush'): Stream.flush ()finally: Self.release ()defemit (self, record):Try: Msg=Self.format (record) stream= Sys.stderrifRecord.levelname = ='ERROR'Elsesys.stdout stream.write (msg) stream.write (self.terminator) Self._flush (stream) exceptBaseexception as Ex:record.msg= Record.getmessage () +'writelogexception:'+Str (ex) Self.handleerror (record)if __name__=="__main__": _logger=logging.root _logger.setlevel (logging.info) Formatter= Logging. Formatter ('% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s') _console_handler=Consolehandler (Logging.info) _console_handler.setformatter (formatter) _logger.addhandler (_console_handler) L Ogging.info ('Info') Logging.error ('Error')
Python3.5 Console log output, differentiating between standard output and error output