Skip to content

logging.StreamHandler produces BrokenPipeError when cut short by head utility #134568

Open
@blhsing

Description

@blhsing

Bug report

Bug description:

The following code:

# test.py
import sys
import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler(sys.stdout))
logger.debug('foo')
logger.debug('bar')

when piped to head -n1, produces:

# python test.py | head -n1
foo
--- Logging error ---
Traceback (most recent call last):
  File "/src/cpython/Lib/logging/__init__.py", line 1155, in emit
    self.flush()
    ~~~~~~~~~~^^
  File "/src/cpython/Lib/logging/__init__.py", line 1137, in flush
    self.stream.flush()
    ~~~~~~~~~~~~~~~~~^^
BrokenPipeError: [Errno 32] Broken pipe
Call stack:
  File "test.py", line 8, in <module>
    logger.debug('bar')
Message: 'bar'
Arguments: ()
Exception ignored while flushing sys.stdout:
BrokenPipeError: [Errno 32] Broken pipe

This is because logging.StreamHandler.emit does not handle BrokenPipeError when flushing the stream.
I will fix this with the approach recommended by Note on SIGPIPE.

CPython versions tested on:

CPython main branch, 3.13

Operating systems tested on:

Linux

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    pendingThe issue will be closed if no feedback is providedstdlibPython modules in the Lib dirtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions