Skip to content

Refactor - Rewrite default logging logic to be an implementation of RequestHookType and ResponseHookType #12

@u-ways

Description

@u-ways

Background

First, please check the source code and the acceptance tests. After getting familiar with the project, analyze the decorate function: https://github.com/u-ways/logging-http-client/blob/main/logging_http_client/http_session.py

In particular:

prepared: PreparedRequest = self.prepare_request(Request(**kwargs))
request_id = prepared.headers.get(X_REQUEST_ID_HEADER, None)
correlation_id = prepared.headers.get(X_CORRELATION_ID_HEADER, None)
source_system = prepared.headers.get(X_SOURCE_HEADER, None)
kwargs.setdefault(HEADERS_KWARG, {})
if request_id is None:
kwargs[HEADERS_KWARG][X_REQUEST_ID_HEADER] = str(uuid.uuid4())
request_id = kwargs[HEADERS_KWARG][X_REQUEST_ID_HEADER]
prepared.headers.update({X_REQUEST_ID_HEADER: request_id})
correlation_id_provider = config.get_correlation_id_provider()
if correlation_id is None and correlation_id_provider is not None:
kwargs[HEADERS_KWARG][X_CORRELATION_ID_HEADER] = correlation_id_provider()
correlation_id = kwargs[HEADERS_KWARG][X_CORRELATION_ID_HEADER]
prepared.headers.update({X_CORRELATION_ID_HEADER: correlation_id})
if source_system is None:
kwargs[HEADERS_KWARG][X_SOURCE_HEADER] = source
source_system = kwargs[HEADERS_KWARG][X_SOURCE_HEADER]
prepared.headers.update({X_SOURCE_HEADER: source_system})
request_logging_hook = config.get_custom_request_logging_hook()
if request_logging_hook is not None:
request_logging_hook(logger, prepared)
else:
if config.is_request_logging_enabled():
logger.info(
msg="REQUEST",
extra=HttpLogRecord.request_processor(
source_system=source_system, request_id=request_id, request=prepared
),
)
# Call the original method... (with modified **kwargs)
response: Response = original_method(**kwargs)
response_logging_hook = config.get_custom_response_logging_hook()
if response_logging_hook is not None:
response_logging_hook(logger, response)
else:
if config.is_response_logging_enabled():
logger.info(
msg="RESPONSE", extra=HttpLogRecord.response_processor(request_id=request_id, response=response)
)
return response

You will notice this logic can be refactored to be a default implementation for:

_request_logging_hook = None
_response_logging_hook = None

This would make the implementation details cleaner, and will prepare us for the next feature request: #14

Metadata

Metadata

Assignees

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions