From f4c09804c7e031f0e486ce7041d573e0ee73b102 Mon Sep 17 00:00:00 2001 From: Gary van der Merwe Date: Wed, 15 Oct 2025 09:43:02 +0200 Subject: [PATCH] When logging exceptions, enable colorized traceback that were introduced in python3.13. --- colorlog/formatter.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/colorlog/formatter.py b/colorlog/formatter.py index f011ca2..8981dbd 100644 --- a/colorlog/formatter.py +++ b/colorlog/formatter.py @@ -4,6 +4,8 @@ import os import sys import typing +import traceback +import io import colorlog.escape_codes @@ -175,6 +177,29 @@ def _append_reset(self, message: str, escapes: EscapeCodes) -> str: return message + if sys.version_info >= (3, 13): + + def formatException(self, ei): + """Format and return the specified exception information as a string.""" + # This is a copy of logging.Formatter.formatException that passes in + # an appropriate value for colorize to print_exception. + + sio = io.StringIO() + tb = ei[2] + traceback.print_exception( + ei[0], + ei[1], + tb, + limit=None, + file=sio, + colorize=not self._blank_escape_codes(), + ) + s = sio.getvalue() + sio.close() + if s[-1:] == "\n": + s = s[:-1] + return s + class LevelFormatter: """An extension of ColoredFormatter that uses per-level format strings."""