Skip to content

Commit

Permalink
Merge pull request #241 from IBM/JsonFormatterSerialization-238
Browse files Browse the repository at this point in the history
[py] Json formatter serialization 238
  • Loading branch information
gabe-l-hart authored Oct 26, 2022
2 parents e1100fc + 2f7fbe3 commit f648069
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/python/alog/alog.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,15 @@ def format(self, record):
if g_thread_id_enabled:
log_record['thread_id'] = threading.get_ident()

# Interpolate message and args if present
record_args = log_record.pop('args', None)
if record_args:
message = log_record.get('message')
if message:
log_record['message'] = message % record_args
else:
log_record['message'] = str(record_args)

return json.dumps(log_record, sort_keys=True)

class AlogPrettyFormatter(AlogFormatterBase):
Expand Down
38 changes: 38 additions & 0 deletions src/python/tests/test_alog.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,44 @@ def test_json_json_level_formatting():
assert 'level' in logged_output[0]
assert logged_output[0]['level'].lower() == logged_output[0]['level']

def test_json_with_functions():
'''Make sure that function arguments are formatted correctly with json'''

# Configure for log capture
capture_formatter = LogCaptureFormatter('json')
alog.configure(default_level='info', formatter=capture_formatter)
test_channel = alog.use_channel('TEST')

# Log a message with a function
test_channel.info('Logging a function %s', is_log_msg)

# Validate that we get a dict back
logged_output = capture_formatter.get_json_records()
assert len(logged_output) == 1
assert isinstance(logged_output[0], dict)
assert 'level' in logged_output[0]
assert logged_output[0]['level'].lower() == logged_output[0]['level']

def test_log_code_json_function():
'''Test that logging with a log code and the json formatter with a function works as expected.
'''
# Configure for log capture
capture_formatter = LogCaptureFormatter('json')
alog.configure(default_level='info', formatter=capture_formatter)
test_channel = alog.use_channel('TEST')

# Log with a code and some functions
test_channel.info(test_code, "Logging 2 functions, %s and %s", is_log_msg, pretty_level_to_name)
logged_output = capture_formatter.get_json_records()

# Make sure the code and message came through as fields
assert len(logged_output) == 1
record = logged_output[0]
assert 'log_code' in record
assert record['log_code'] == test_code
assert 'message' in record
assert record['message'] == f"Logging 2 functions, {is_log_msg} and {pretty_level_to_name}"

## Custom Formatter ############################################################

def test_custom_formatter_pretty_with_args():
Expand Down

0 comments on commit f648069

Please sign in to comment.