Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / Python

logging.exception

exception regista um evento ERROR com exc_info=True por omissão.

Versão: Python 3.14; repository image, production runtime not attested

Sintaxe

logging.exception(msg, *args, exc_info=True, **kwargs)

exception regista um evento ERROR com exc_info=True por omissão.

Dentro de except, acrescenta o rastreio da exceção ativa sem a lançar novamente. exc_info=False omite esse detalhe.

Quando int('x') falha, o exemplo encontra parse e ValueError e imprime True True.

import logging,io
o=io.StringIO()
logging.basicConfig(stream=o,format='%(levelname)s %(message)s',force=True)
try: int('x')
except ValueError:
    logging.exception('parse')
    assert 'ERROR parse' in o.getvalue() and 'Traceback' in o.getvalue() and 'ValueError' in o.getvalue()
    o.seek(0);o.truncate()
    logging.exception('short',exc_info=False)
assert o.getvalue()=='ERROR short\n'

Exemplos

import logging
from io import StringIO

out = StringIO()
logging.basicConfig(stream=out, force=True)
try:
    int("x")
except ValueError:
    logging.exception("parse")
print("ValueError" in out.getvalue(), "parse" in out.getvalue())

Resultado

True True

Quando int('x') falha, o exemplo encontra parse e ValueError e imprime True True.

Fontes