A handler class which writes logging records, appropriately formatted, to a stream. Note that this class does not close the stream, as sys.stdout or sys.stderr may be used.
| 1065 | return '<%s (%s)>' % (self.__class__.__name__, level) |
| 1066 | |
| 1067 | class StreamHandler(Handler): |
| 1068 | """ |
| 1069 | A handler class which writes logging records, appropriately formatted, |
| 1070 | to a stream. Note that this class does not close the stream, as |
| 1071 | sys.stdout or sys.stderr may be used. |
| 1072 | """ |
| 1073 | |
| 1074 | terminator = '\n' |
| 1075 | |
| 1076 | def __init__(self, stream=None): |
| 1077 | """ |
| 1078 | Initialize the handler. |
| 1079 | |
| 1080 | If stream is not specified, sys.stderr is used. |
| 1081 | """ |
| 1082 | Handler.__init__(self) |
| 1083 | if stream is None: |
| 1084 | stream = sys.stderr |
| 1085 | self.stream = stream |
| 1086 | |
| 1087 | def flush(self): |
| 1088 | """ |
| 1089 | Flushes the stream. |
| 1090 | """ |
| 1091 | self.acquire() |
| 1092 | try: |
| 1093 | if self.stream and hasattr(self.stream, "flush"): |
| 1094 | self.stream.flush() |
| 1095 | finally: |
| 1096 | self.release() |
| 1097 | |
| 1098 | def emit(self, record): |
| 1099 | """ |
| 1100 | Emit a record. |
| 1101 | |
| 1102 | If a formatter is specified, it is used to format the record. |
| 1103 | The record is then written to the stream with a trailing newline. If |
| 1104 | exception information is present, it is formatted using |
| 1105 | traceback.print_exception and appended to the stream. If the stream |
| 1106 | has an 'encoding' attribute, it is used to determine how to do the |
| 1107 | output to the stream. |
| 1108 | """ |
| 1109 | try: |
| 1110 | msg = self.format(record) |
| 1111 | stream = self.stream |
| 1112 | # issue 35046: merged two stream.writes into one. |
| 1113 | stream.write(msg + self.terminator) |
| 1114 | self.flush() |
| 1115 | except RecursionError: # See issue 36272 |
| 1116 | raise |
| 1117 | except Exception: |
| 1118 | self.handleError(record) |
| 1119 | |
| 1120 | def setStream(self, stream): |
| 1121 | """ |
| 1122 | Sets the StreamHandler's stream to the specified value, |
| 1123 | if it is different. |
| 1124 |