Skip to content

Commit 733a8c1

Browse files
committed
fixup! feat: allow specifying excluded ignored_keys
1 parent eb43494 commit 733a8c1

File tree

1 file changed

+16
-16
lines changed

1 file changed

+16
-16
lines changed

src/logfmter/formatter.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -141,44 +141,39 @@ def normalize_key(cls, key: str) -> str:
141141

142142
return key.replace(" ", "_").replace("\n", "\\n")
143143

144-
def get_extra(self, record: logging.LogRecord) -> dict:
144+
@classmethod
145+
def get_extra(cls, record: logging.LogRecord) -> dict:
145146
"""
146147
Return a dictionary of logger extra parameters by filtering any reserved keys.
147148
"""
148149
extras = {}
149150

150151
for key, value in record.__dict__.items():
151-
if key in self.ignored_keys:
152-
continue
153-
key = self.normalize_key(key)
152+
key = cls.normalize_key(key)
154153

155154
if key in RESERVED:
156155
continue
157156

158157
if isinstance(value, dict):
159-
extras.update(self.flatten_dict(value, key))
158+
extras.update(cls.flatten_dict(value, key))
160159
else:
161160
extras[key] = value
162161

163162
return extras
164163

165-
def flatten_dict(self, v: dict, root: str = "") -> dict[str, Any]:
164+
@classmethod
165+
def flatten_dict(cls, v: dict, root: str = "") -> dict[str, Any]:
166166
"""
167167
Return a dictionary whereby the input dictionary is converted to
168168
depth equal to one with keys that are joined via periods.
169169
"""
170170
flattened = {}
171171

172172
for key, value in v.items():
173-
key = (
174-
f"{root}.{self.normalize_key(key)}" if root else self.normalize_key(key)
175-
)
176-
177-
if key in self.ignored_keys:
178-
continue
173+
key = f"{root}.{cls.normalize_key(key)}" if root else cls.normalize_key(key)
179174

180175
if isinstance(value, dict):
181-
flattened.update(self.flatten_dict(value, key))
176+
flattened.update(cls.flatten_dict(value, key))
182177
else:
183178
flattened[key] = value
184179

@@ -211,8 +206,6 @@ def format(self, record: logging.LogRecord) -> str:
211206

212207
if isinstance(record.msg, dict):
213208
params = self.flatten_dict(record.msg)
214-
elif "msg" in self.ignored_keys:
215-
params = {}
216209
else:
217210
params = {"msg": record.getMessage()}
218211

@@ -251,7 +244,14 @@ def format(self, record: logging.LogRecord) -> str:
251244

252245
tokens.append("{}={}".format(key, self.format_value(value)))
253246

254-
formatted_params = self.format_params(params)
247+
formatted_params = self.format_params(
248+
{
249+
k: v
250+
for k, v in params.items()
251+
if k not in self.ignored_keys
252+
and k.split(".", 1)[0] not in self.ignored_keys
253+
}
254+
)
255255
if formatted_params:
256256
tokens.append(formatted_params)
257257

0 commit comments

Comments
 (0)