-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix: Log request body (#6404) #6536
base: develop
Are you sure you want to change the base?
Conversation
f7083d1
to
2246652
Compare
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## develop #6536 +/- ##
===========================================
+ Coverage 85.35% 85.36% +0.01%
===========================================
Files 155 155
Lines 20779 20794 +15
===========================================
+ Hits 17735 17751 +16
+ Misses 3044 3043 -1 ☔ View full report in Codecov by Sentry. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Currently the logging tests only cover GET requests. Consider adding a logging test of a PUT or POST request with a body. Maybe this can be done in IT when a manifest request is made, or against a dummy endpoint like in TestAppLogging.test
src/azul/chalice.py
Outdated
else: | ||
if config.debug == 2: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
else: | |
if config.debug == 2: | |
elif config.debug == 2: |
2395ab7
to
6d3f998
Compare
test/service/test_app_logging.py
Outdated
def test_request_logs(self): | ||
for level in INFO, DEBUG: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Instead of having two loops for level
and azul_debug
, how about you only loop over the three values of azul_debug
:
def test_request_logs(self):
for azul_debug in (0, 1, 2):
for authenticated in False, True:
for request_body in False, True:
headers = {'authorization': 'Bearer foo_token'} if authenticated else {}
if request_body:
request_body = json.dumps({'filters': json.dumps({'organ': {'is': ['foo']}})})
headers = {
'content-length': str(len(request_body)),
'content-type': 'application/json',
**headers,
}
with mock_patch.object(Config,
'debug',
new=PropertyMock(return_value=azul_debug)):
self._assert_request_logs(authenticated, request_body, headers, azul_debug)
then in _assert_request_logs
you can set level
based on azul_debug
:
level = [INFO, DEBUG, DEBUG][azul_debug]
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Great idea, ty!
test/service/test_app_logging.py
Outdated
@@ -3,15 +3,22 @@ | |||
DEBUG, | |||
INFO, | |||
) | |||
from unittest.mock import ( | |||
PropertyMock, | |||
patch as mock_patch, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
patch as mock_patch, | |
patch, |
What's wrong with patch
?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I felt compelled to denote the mock relationship to patch.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We don't do that anywhere else and I see no good reason to start now.
src/azul/chalice.py
Outdated
body = json.dumps(body, cls=self._LogJSONEncoder) | ||
msg = f' ({len(body)} characters)' | ||
else: | ||
msg = f' (first {str(n := 1024)} characters)' |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
msg = f' (first {str(n := 1024)} characters)' | |
n = 1024 | |
msg = f' (first {str(n)} characters)' |
The walrus operator can be useful in an if
condition, but here seems unnecessary and the code is easier to read without it.
0e6add6
to
cd97e59
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Approved.
b939169
to
10b6f76
Compare
src/azul/chalice.py
Outdated
context['httpMethod'], | ||
context['path'], | ||
json.dumps(request_info, cls=self._LogJSONEncoder)) | ||
|
||
body = self.current_request.json_body | ||
if not body: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Isn't this conflating None and the empty string? And for responses, don't we log the fact that the body is absent?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Isn't this conflating None and the empty string?
My bad, it skipped me, ty.
And for responses, don't we log the fact that the body is absent?
Yeah, the http_body_log_message
gracefully handles that aspect:
Lines 168 to 175 in ccc785f
def http_body_log_message(body_type: str, | |
body: bytes | bytearray | str | None, | |
*, | |
verbatim: bool = False, | |
) -> str: | |
if body is None: | |
return f'… without {body_type} body' | |
elif isinstance(body, (bytes, bytearray, str)): |
I've renamed the msg
variable to body_len_msg
, with the intent of making the purpose of the variable more evident.
test/service/test_app_logging.py
Outdated
'Returning 200 response with headers {"Access-Control-Allow-Origin": ' | ||
'"*", "Access-Control-Allow-Headers": ' | ||
'"Authorization,Content-Type,X-Amz-Date,X-Amz-Security-Token,X-Api-Key", ' | ||
f'"Content-Security-Policy": "default-src {sq("self")}", ' | ||
'"Referrer-Policy": "strict-origin-when-cross-origin", ' | ||
'"Strict-Transport-Security": "max-age=63072000; includeSubDomains; preload", ' | ||
'"X-Content-Type-Options": "nosniff", ' | ||
'"X-Frame-Options": "DENY", ' | ||
'"X-XSS-Protection": "1; mode=block", ' | ||
'"Cache-Control": "no-store"}. ' | ||
'See next line for the first 1024 characters of the body.\n' | ||
'{"pagination": {"count": 1, "total": 1, "size": 10, "next": null, "previous":' | ||
' null, "pages": 1, "sort": "projectTitle", "order": "asc"}, "termFacets": ' | ||
'{"organ": {"terms": [{"term": "pancreas", "count": 1}], "total": 1, "type": ' | ||
'"terms"}, "sampleEntityType": {"terms": [{"term": "specimens", "count": 1}], ' | ||
'"total": 1, "type": "terms"}, "dataUseRestriction": {"terms": [{"term": null, ' | ||
'"count": 1}], "total": 1, "type": "terms"}, "project": {"terms": [{"term": ' | ||
'"Single of human pancreas", "count": 1, "projectId": ' | ||
'["e8642221-4c2c-4fd7-b926-a68bce363c88"]}], "total": 1, "type": "terms"}, ' | ||
'"sampleDisease": {"terms": [{"term": "normal", "count": 1}], "total": 1, "type": ' | ||
'"terms"}, "nucleicAcidSource": {"terms": [{"term": "single cell", "count": 1}], ' | ||
'"total": 1, "type": "terms"}, "assayType": {"terms": [{"term": null, "count": 1}], ' | ||
'"total": 0, "type": "terms"}, "instrumentManufacturerModel": {"terms": [{"term": ' | ||
'"Illumina NextSeq 500", "count": 1}], "total": 1, "type": "terms"}, "institution": ' | ||
'{"terms": [{"term": "Farmers Tru', |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please find a way to make this less ugly. For example, you could specify headers and body as JSON literals and use json.dumps() to convert them to a string, and taking only the first 1024 charterers of the body.
test/service/test_app_logging.py
Outdated
'{"up": true}' | ||
) | ||
]) | ||
if reques_body: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
if reques_body: | |
if request_body: |
test/service/test_app_logging.py
Outdated
with self.subTest(level=level, | ||
authenticated=authenticated, | ||
request_body=reques_body, | ||
azul_debug=azul_debug): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
with self.subTest(level=level, | |
authenticated=authenticated, | |
request_body=reques_body, | |
azul_debug=azul_debug): | |
with self.subTest(authenticated=authenticated, | |
request_body=reques_body, | |
azul_debug=azul_debug): |
because level
is derived from azul_debug
you don't need to label the subtest with it.
3969986
to
437f818
Compare
src/azul/chalice.py
Outdated
log.info('%s%s', | ||
http_body_log_message('request', body, verbatim=True), body_len_msg) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
log.info('%s%s', | |
http_body_log_message('request', body, verbatim=True), body_len_msg) | |
log.info(http_body_log_message('request', body, verbatim=True) + body_len_msg)) |
test/service/test_app_logging.py
Outdated
}, | ||
'termFacets': { | ||
'organ': { | ||
'terms': [{ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What's your convention about hugging brackets and braces? Hugging them breaks our wrap-all-or-nothing convention so if you already break it, you might as well put each inner-most dict literals on one line.
Or, don't hug.
test/service/test_app_logging.py
Outdated
'"X-XSS-Protection": "1; mode=block", ' | ||
'"Cache-Control": "no-store"}. ' | ||
'See next line for the first 1024 characters of the body.\n' | ||
+ json_head(1024, { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
As I pointed out before, you shouldn't use the code under test to compute an assertion about the output of said code.
cc35a8b
to
730d487
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We should discuss in PL how we can match up the different levels of detail logged at which log level for the request and response. Currently these two methods look worryingly dissimilar.
src/azul/chalice.py
Outdated
body = self.current_request.json_body | ||
if body is None: | ||
len_msg = '' | ||
elif config.debug == 2: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
elif config.debug == 2: | |
elif config.debug > 1: |
If we ever add a fourth level m we would want this condition to be True there as well.
src/azul/chalice.py
Outdated
n = 1024 | ||
len_msg = f' (first {str(n)} characters)' | ||
body = json_head(n, body) if not isinstance(body, str | bytes) else body[:n] | ||
log.info('%s', http_body_log_message('request', body, verbatim=True) + len_msg) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
log.info('%s', http_body_log_message('request', body, verbatim=True) + len_msg) | |
log.info(http_body_log_message('request', body, verbatim=True) + len_msg) |
src/azul/chalice.py
Outdated
len_msg = f' ({len(body)} characters)' | ||
else: | ||
n = 1024 | ||
len_msg = f' (first {str(n)} characters)' |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
len_msg = f' (first {str(n)} characters)' | |
len_msg = f' (first {n} characters)' |
730d487
to
e4bd1b6
Compare
Connected issues: #6404
Checklist
Author
develop
issues/<GitHub handle of author>/<issue#>-<slug>
1 when the issue title describes a problem, the corresponding PR
title is
Fix:
followed by the issue titleAuthor (partiality)
p
tag to titles of partial commitspartial
or completely resolves all connected issuespartial
labelAuthor (chains)
base
or this PR is not chained to another PRchained
or is not chained to another PRAuthor (reindex, API changes)
r
tag to commit title or the changes introduced by this PR will not require reindexing of any deploymentreindex:dev
or the changes introduced by it will not require reindexing ofdev
reindex:anvildev
or the changes introduced by it will not require reindexing ofanvildev
reindex:anvilprod
or the changes introduced by it will not require reindexing ofanvilprod
reindex:prod
or the changes introduced by it will not require reindexing ofprod
reindex:partial
and its description documents the specific reindexing procedure fordev
,anvildev
,anvilprod
andprod
or requires a full reindex or carries none of the labelsreindex:dev
,reindex:anvildev
,reindex:anvilprod
andreindex:prod
API
or this PR does not modify a REST APIa
(A
) tag to commit title for backwards (in)compatible changes or this PR does not modify a REST APIapp.py
or this PR does not modify a REST APIAuthor (upgrading deployments)
make docker_images.json
and committed the resulting changes or this PR does not modifyazul_docker_images
, or any other variables referenced in the definition of that variableu
tag to commit title or this PR does not require upgrading deploymentsupgrade
or does not require upgrading deploymentsdeploy:shared
or does not modifydocker_images.json
, and does not require deploying theshared
component for any other reasondeploy:gitlab
or does not require deploying thegitlab
componentdeploy:runner
or does not require deploying therunner
imageAuthor (hotfixes)
F
tag to main commit title or this PR does not include permanent fix for a temporary hotfixanvilprod
andprod
) have temporary hotfixes for any of the issues connected to this PRAuthor (before every review)
develop
, squashed old fixupsmake requirements_update
or this PR does not modifyrequirements*.txt
,common.mk
,Makefile
andDockerfile
R
tag to commit title or this PR does not modifyrequirements*.txt
reqs
or does not modifyrequirements*.txt
make integration_test
passes in personal deployment or this PR does not modify functionality that could affect the IT outcomePeer reviewer (after approval)
System administrator (after approval)
demo
orno demo
no demo
no sandbox
N reviews
label is accurateOperator (before pushing merge the commit)
reindex:…
labels andr
commit title tagno demo
develop
_select dev.shared && CI_COMMIT_REF_NAME=develop make -C terraform/shared apply_keep_unused
or this PR is not labeleddeploy:shared
_select dev.gitlab && CI_COMMIT_REF_NAME=develop make -C terraform/gitlab apply
or this PR is not labeleddeploy:gitlab
_select anvildev.shared && CI_COMMIT_REF_NAME=develop make -C terraform/shared apply_keep_unused
or this PR is not labeleddeploy:shared
_select anvildev.gitlab && CI_COMMIT_REF_NAME=develop make -C terraform/gitlab apply
or this PR is not labeleddeploy:gitlab
deploy:gitlab
deploy:gitlab
System administrator
dev.gitlab
are complete or this PR is not labeleddeploy:gitlab
anvildev.gitlab
are complete or this PR is not labeleddeploy:gitlab
Operator (before pushing merge the commit)
_select dev.gitlab && make -C terraform/gitlab/runner
or this PR is not labeleddeploy:runner
_select anvildev.gitlab && make -C terraform/gitlab/runner
or this PR is not labeleddeploy:runner
sandbox
label or PR is labeledno sandbox
dev
or PR is labeledno sandbox
anvildev
or PR is labeledno sandbox
sandbox
deployment or PR is labeledno sandbox
anvilbox
deployment or PR is labeledno sandbox
sandbox
deployment or PR is labeledno sandbox
anvilbox
deployment or PR is labeledno sandbox
sandbox
or this PR does not remove catalogs or otherwise causes unreferenced indices indev
anvilbox
or this PR does not remove catalogs or otherwise causes unreferenced indices inanvildev
sandbox
or this PR is not labeledreindex:dev
anvilbox
or this PR is not labeledreindex:anvildev
sandbox
or this PR is not labeledreindex:dev
anvilbox
or this PR is not labeledreindex:anvildev
p
if the PR is also labeledpartial
Operator (chain shortening)
develop
or this PR is not labeledbase
chained
label from the blocked PR or this PR is not labeledbase
base
base
label from this PR or this PR is not labeledbase
Operator (after pushing the merge commit)
dev
anvildev
dev
dev
anvildev
anvildev
_select dev.shared && make -C terraform/shared apply
or this PR is not labeleddeploy:shared
_select anvildev.shared && make -C terraform/shared apply
or this PR is not labeleddeploy:shared
dev
anvildev
Operator (reindex)
dev
or this PR is neither labeledreindex:partial
norreindex:dev
anvildev
or this PR is neither labeledreindex:partial
norreindex:anvildev
dev
or this PR is neither labeledreindex:partial
norreindex:dev
anvildev
or this PR is neither labeledreindex:partial
norreindex:anvildev
dev
or this PR is neither labeledreindex:partial
norreindex:dev
anvildev
or this PR is neither labeledreindex:partial
norreindex:anvildev
dev
or this PR does not require reindexingdev
anvildev
or this PR does not require reindexinganvildev
dev
or this PR does not require reindexingdev
anvildev
or this PR does not require reindexinganvildev
dev
or this PR does not require reindexingdev
anvildev
or this PR does not require reindexinganvildev
Operator
deploy:shared
,deploy:gitlab
,deploy:runner
,API
,reindex:partial
,reindex:anvilprod
andreindex:prod
labels to the next promotion PRs or this PR carries none of these labelsdeploy:shared
,deploy:gitlab
,deploy:runner
,API
,reindex:partial
,reindex:anvilprod
andreindex:prod
labels, from the description of this PR to that of the next promotion PRs or this PR carries none of these labelsShorthand for review comments
L
line is too longW
line wrapping is wrongQ
bad quotesF
other formatting problem