Skip to content

Commit 666455f

Browse files
committed
Add support for adding callables as extra fields
1 parent 49635e1 commit 666455f

File tree

3 files changed

+12
-2
lines changed

3 files changed

+12
-2
lines changed

docs/config.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,11 @@ Options:
225225
to Logstash. This dictionary will be merged with any other extra
226226
items passed in the logging call.
227227

228+
Note that you can also put a callable with zero arguments. If that is
229+
the case, the callable will be evaluated at the moment you log this thing
230+
(ie. not in the submitter thread). If this callable returns None, extra
231+
field will be skipped.
232+
228233
*Type*: ``dict``
229234

230235
*Default*: None

logstash_async/formatter.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,11 @@ def _get_extra_fields(self, record):
202202
}
203203
# static extra fields
204204
if self._extra:
205-
extra_fields.update(self._extra)
205+
for field_name, field_value in self._extra.items():
206+
if callable(field_value):
207+
field_value = field_value()
208+
if field_value is not None:
209+
extra_fields[field_name] = field_value
206210
if getattr(record, 'taskName', None):
207211
extra_fields[Schema.TASK_NAME] = record.taskName
208212
# exceptions

tests/formatter_test.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ def test_format_timestamp_microsecond_2(self):
9494

9595
@patch.object(LogstashFormatter, '_format_exception', lambda s, e: e)
9696
def test_default_schema(self):
97-
formatter = LogstashFormatter(tags=['t1', 't2'])
97+
formatter = LogstashFormatter(tags=['t1', 't2'], extra={'value': lambda: 5})
9898
result = formatter._format_to_dict(create_log_record())
9999
self.assertDictEqual(result, {
100100
'@timestamp': '2021-10-24T13:32:15.024Z',
@@ -108,6 +108,7 @@ def test_default_schema(self):
108108
'type': 'python-logstash',
109109
'tags': ['t1', 't2'],
110110
'extra': {
111+
'value': 5,
111112
'func_name': 'f',
112113
'interpreter': sys.executable,
113114
'interpreter_version': _interpreter_version,

0 commit comments

Comments
 (0)