Skip to content

Commit 949038b

Browse files
authored
feat: use already calculated exc_text
1 parent aea8fb4 commit 949038b

File tree

2 files changed

+8
-23
lines changed

2 files changed

+8
-23
lines changed

src/logfmter/formatter.py

Lines changed: 5 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import logging
22
import numbers
3-
import traceback
43
from types import TracebackType
54
from typing import Any, Dict, List, Optional, Tuple, Type, cast
65

@@ -92,25 +91,6 @@ def format_value(cls, value) -> str:
9291

9392
return cls.format_string(str(value))
9493

95-
@classmethod
96-
def format_exc_info(cls, exc_info: ExcInfo) -> str:
97-
"""
98-
Format the provided exc_info into a logfmt formatted string.
99-
100-
This function should only be used to format exceptions which are
101-
currently being handled. Not with those exceptions which are
102-
manually passed into the logger. For example:
103-
104-
try:
105-
raise Exception()
106-
except Exception:
107-
logging.exception()
108-
"""
109-
# Tracebacks have a single trailing newline that we don't need.
110-
value = "".join(traceback.format_exception(*exc_info)).rstrip("\n")
111-
112-
return cls.format_string(value)
113-
11494
@classmethod
11595
def format_params(cls, params: dict) -> str:
11696
"""
@@ -246,10 +226,13 @@ def format(self, record: logging.LogRecord) -> str:
246226
if formatted_params:
247227
tokens.append(formatted_params)
248228

249-
if record.exc_info:
229+
if record.exc_info and not record.exc_text:
250230
# Cast exc_info to its not null variant to make mypy happy.
251231
exc_info = cast(ExcInfo, record.exc_info)
252-
tokens.append(f"exc_info={self.format_exc_info(exc_info)}")
232+
record.exc_text = self.formatException(exc_info)
233+
234+
if record.exc_text:
235+
tokens.append(f"exc_info={self.format_string(record.exc_text)}")
253236

254237
if record.stack_info:
255238
stack_info = self.formatStack(record.stack_info).rstrip("\n")

tests/test_formatter.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,9 @@ def test_format_exc_info():
6969
except Exception:
7070
exc_info = sys.exc_info()
7171

72-
value = Logfmter().format_exc_info(exc_info)
72+
record = logging.makeLogRecord({"msg": "Error", "exc_info": exc_info})
73+
value = Logfmter().format(record)
74+
_prefix, _, value = value.partition("exc_info=")
7375

7476
assert value.startswith('"') and value.endswith('"')
7577

0 commit comments

Comments
 (0)