CKTIS / Python
logging.StreamHandler
Writes formatted log records to a text stream with a terminating string.
Version: Python 3.14; repository image, production runtime not attested
Syntax
logging.StreamHandler(stream=None)Writes formatted log records to a text stream with a terminating string.
Replacing the handler terminator changes how successive records are separated. The stream must accept text writes.
The default target is sys.stderr. emit writes the formatted record and terminator, normally a newline, then flushes. setStream flushes the old stream and returns it on a change, or returns None for the same stream. Closing the handler does not close a supplied stream. A vertical bar yields a|b|.
import logging,io,sys
a,b=io.StringIO(),io.StringIO()
h=logging.StreamHandler(a)
assert logging.StreamHandler().stream is sys.stderr
r=logging.LogRecord('app',20,'',0,'one',(),None)
h.emit(r)
assert a.getvalue()=='one\n' and h.setStream(b) is a and h.setStream(b) is None
h.terminator='|'
h.emit(r)
h.close()
assert b.getvalue()=='one|' and not b.closed
Examples
import logging
from io import StringIO
out = StringIO()
h = logging.StreamHandler(out)
h.terminator = "|"
log = logging.getLogger("capture")
log.propagate = False
log.addHandler(h)
log.warning("a")
log.warning("b")
print(out.getvalue())
Result
a|b|
The default target is sys.stderr. emit writes the formatted record and terminator, normally a newline, then flushes. setStream flushes the old stream and returns it on a change, or returns None for the same stream. Closing the handler does not close a supplied stream. A vertical bar yields a|b|.