python / python/cpython

logging.StreamHandler produces BrokenPipeError when cut short by head utility

Aperta
#134,568 6 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

pending stdlib type-bug
Lingua principale
Python
Stelle
77.2k
Fork
35.9k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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
  • gh-134569

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Il percorso segnalato è Lib/logging/init.py, in particolare StreamHandler.emit e flush; riproduci il problema eseguendo test.py con l'output reindirizzato a head -n1 su Linux. Confronta la correzione proposta nella PR collegata gh-134569 e i relativi test; il lavoro è completo quando la pipeline breve non emette più il traceback di logging né il BrokenPipeError finale.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
tooling
Tipo di issue
Bug
Difficoltà
3/5
Tempo stimato
1-2 giorni
Stato di attività
Ferma
Chiarezza
Specificata chiaramente
Idoneità per principianti
25/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.