forked from OCA/rest-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Split logging features of fastapi_log #8
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
Open
SirPyTech
wants to merge
5
commits into
akretion:16.0-add-fastapi_log
Choose a base branch
from
PyTech-SRL:16.0-add-fastapi_log
base: 16.0-add-fastapi_log
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
86c7696
[REF] fastapi_log: Extract common features to `api_log`
SirPyTech 81168a1
[ADD] fastapi_log_mail
SirPyTech 9ee914c
[FIX] fastapi_log: Manage multi-slash endpoints
SirPyTech 64598a4
[DON'T MERGE] test-requirements.txt
SirPyTech 05fb39b
[IMP] api_log: Hide sensitive headers
SirPyTech File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
======= | ||
API Log | ||
======= | ||
|
||
.. | ||
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! | ||
!! This file is generated by oca-gen-addon-readme !! | ||
!! changes will be overwritten. !! | ||
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! | ||
!! source digest: sha256:ef0c0bceb8ae27bcfebaebc22e2fb4747475f2a2c60dd2d410bc40b6efee9b6a | ||
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! | ||
|
||
.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png | ||
:target: https://odoo-community.org/page/development-status | ||
:alt: Beta | ||
.. |badge2| image:: https://img.shields.io/badge/licence-AGPL--3-blue.png | ||
:target: http://www.gnu.org/licenses/agpl-3.0-standalone.html | ||
:alt: License: AGPL-3 | ||
.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Frest--framework-lightgray.png?logo=github | ||
:target: https://github.com/OCA/rest-framework/tree/16.0/api_log | ||
:alt: OCA/rest-framework | ||
.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png | ||
:target: https://translation.odoo-community.org/projects/rest-framework-16-0/rest-framework-16-0-api_log | ||
:alt: Translate me on Weblate | ||
.. |badge5| image:: https://img.shields.io/badge/runboat-Try%20me-875A7B.png | ||
:target: https://runboat.odoo-community.org/builds?repo=OCA/rest-framework&target_branch=16.0 | ||
:alt: Try me on Runboat | ||
|
||
|badge1| |badge2| |badge3| |badge4| |badge5| | ||
|
||
This module allows to store request and response logs for any API. | ||
|
||
**Table of contents** | ||
|
||
.. contents:: | ||
:local: | ||
|
||
Bug Tracker | ||
=========== | ||
|
||
Bugs are tracked on `GitHub Issues <https://github.com/OCA/rest-framework/issues>`_. | ||
In case of trouble, please check there if your issue has already been reported. | ||
If you spotted it first, help us to smash it by providing a detailed and welcomed | ||
`feedback <https://github.com/OCA/rest-framework/issues/new?body=module:%20api_log%0Aversion:%2016.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**>`_. | ||
|
||
Do not contact contributors directly about support or help with technical issues. | ||
|
||
Credits | ||
======= | ||
|
||
Authors | ||
------- | ||
|
||
* Akretion | ||
|
||
Contributors | ||
------------ | ||
|
||
- Florian Mounier [email protected] | ||
|
||
Maintainers | ||
----------- | ||
|
||
This module is maintained by the OCA. | ||
|
||
.. image:: https://odoo-community.org/logo.png | ||
:alt: Odoo Community Association | ||
:target: https://odoo-community.org | ||
|
||
OCA, or the Odoo Community Association, is a nonprofit organization whose | ||
mission is to support the collaborative development of Odoo features and | ||
promote its widespread use. | ||
|
||
.. |maintainer-paradoxxxzero| image:: https://github.com/paradoxxxzero.png?size=40px | ||
:target: https://github.com/paradoxxxzero | ||
:alt: paradoxxxzero | ||
|
||
Current `maintainer <https://odoo-community.org/page/maintainer-role>`__: | ||
|
||
|maintainer-paradoxxxzero| | ||
|
||
This module is part of the `OCA/rest-framework <https://github.com/OCA/rest-framework/tree/16.0/api_log>`_ project on GitHub. | ||
|
||
You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
from . import models |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
# Copyright 2025 Akretion (http://www.akretion.com). | ||
# @author Florian Mounier <[email protected]> | ||
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). | ||
|
||
{ | ||
"name": "API Log", | ||
"version": "16.0.1.0.0", | ||
"author": "Akretion, Odoo Community Association (OCA)", | ||
"license": "AGPL-3", | ||
"summary": "Log API requests in database", | ||
"category": "Tools", | ||
"depends": ["web"], | ||
"website": "https://github.com/OCA/rest-framework", | ||
"data": [ | ||
"security/res_groups.xml", | ||
"security/ir_model_access.xml", | ||
"views/api_log_views.xml", | ||
], | ||
"maintainers": ["paradoxxxzero"], | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
from . import api_log |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,224 @@ | ||
# Copyright 2025 Akretion (http://www.akretion.com). | ||
# @author Florian Mounier <[email protected]> | ||
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). | ||
import base64 | ||
import json | ||
import time | ||
from traceback import format_exception | ||
|
||
from werkzeug.exceptions import HTTPException as WerkzeugHTTPException | ||
|
||
from odoo import api, fields, models | ||
|
||
|
||
class APILog(models.Model): | ||
_name = "api.log" | ||
_description = "Log for API" | ||
|
||
# Request | ||
request_url = fields.Char() | ||
request_method = fields.Char() | ||
request_headers = fields.Json() | ||
request_body = fields.Binary(attachment=False) | ||
request_date = fields.Datetime() | ||
request_time = fields.Float() | ||
|
||
# Response | ||
response_status_code = fields.Integer() | ||
response_headers = fields.Json() | ||
response_body = fields.Binary(attachment=False) | ||
response_date = fields.Datetime() | ||
response_time = fields.Float() | ||
|
||
stack_trace = fields.Text() | ||
|
||
# Derived fields | ||
name = fields.Char(compute="_compute_name", store=True) | ||
time = fields.Float(compute="_compute_time", store=True) | ||
request_preview = fields.Text(compute="_compute_request_preview") | ||
response_preview = fields.Text(compute="_compute_response_preview") | ||
request_b64 = fields.Binary( | ||
string="Request Content", compute="_compute_request_b64" | ||
) | ||
response_b64 = fields.Binary( | ||
string="Response Content", compute="_compute_response_b64" | ||
) | ||
request_headers_preview = fields.Text(compute="_compute_headers_preview") | ||
response_headers_preview = fields.Text(compute="_compute_headers_preview") | ||
request_content_type = fields.Char( | ||
compute="_compute_request_headers_derived", store=True | ||
) | ||
request_content_length = fields.Integer( | ||
compute="_compute_request_headers_derived", store=True | ||
) | ||
referrer = fields.Char(compute="_compute_request_headers_derived", store=True) | ||
response_content_type = fields.Char( | ||
compute="_compute_response_headers_derived", store=True | ||
) | ||
response_content_length = fields.Integer( | ||
compute="_compute_response_headers_derived", store=True | ||
) | ||
|
||
@api.model | ||
def _headers_hidden_keys(self): | ||
"""Header keys that should not be logged. | ||
|
||
They might contains sensitive data. | ||
""" | ||
return ( | ||
"Api-Key", | ||
"Cookie", | ||
) | ||
|
||
@api.model | ||
def _sanitize_headers_dict(self, headers_dict): | ||
keys_to_hide = self._headers_hidden_keys() | ||
for key in headers_dict: | ||
if key in keys_to_hide: | ||
headers_dict[key] = "<redacted>" | ||
return headers_dict | ||
|
||
@api.model | ||
def _headers_to_dict(self, headers): | ||
try: | ||
headers_dict = {key: value for key, value in headers.items()} | ||
return self._sanitize_headers_dict(headers_dict) | ||
except AttributeError: | ||
return {} | ||
|
||
def _current_time(self): | ||
return time.time_ns() / 1e9 | ||
|
||
@api.model | ||
def _get_http_request(self, request): | ||
return request.httprequest | ||
|
||
@api.model | ||
def _get_request_body(self, request): | ||
"""Take extra care with the request's body because it might get consumed.""" | ||
httprequest = self._get_http_request(request) | ||
return httprequest.data | ||
|
||
@api.model | ||
def log_request(self, request): | ||
httprequest = self._get_http_request(request) | ||
log_request_values = { | ||
"request_url": httprequest.url, | ||
"request_method": httprequest.method, | ||
"request_headers": self._headers_to_dict(httprequest.headers), | ||
"request_body": self._get_request_body(request), | ||
"request_date": fields.Datetime.now(), | ||
"request_time": self._current_time(), | ||
} | ||
return self.create(log_request_values) | ||
|
||
def log_response(self, response): | ||
log_response_values = { | ||
"response_status_code": response.status_code, | ||
"response_headers": self._headers_to_dict(response.headers), | ||
"response_body": response.data, | ||
"response_date": fields.Datetime.now(), | ||
"response_time": self._current_time(), | ||
} | ||
return self.write(log_response_values) | ||
|
||
def _prepare_log_exception(self, exception): | ||
values = { | ||
"stack_trace": "".join(format_exception(exception)), | ||
"response_body": str(exception), | ||
"response_date": fields.Datetime.now(), | ||
"response_time": self._current_time(), | ||
} | ||
|
||
if isinstance(exception, WerkzeugHTTPException): | ||
values.update( | ||
{ | ||
"response_status_code": exception.code, | ||
"response_headers": self._headers_to_dict(exception.get_headers()), | ||
"response_body": exception.get_body(), | ||
} | ||
) | ||
return values | ||
|
||
def log_exception(self, exception): | ||
try: | ||
exc_handling_response = self.env.registry["ir.http"]._handle_error( | ||
exception | ||
) | ||
self.log_response(exc_handling_response) | ||
except Exception as handling_exception: | ||
exception = handling_exception | ||
log_exception_values = self._prepare_log_exception(exception) | ||
return self.write(log_exception_values) | ||
|
||
@api.depends("request_url", "request_method", "request_date") | ||
def _compute_name(self): | ||
for log in self: | ||
log.name = ( | ||
f"{log.request_date.isoformat()} - " | ||
f"[{log.request_method}] {log.request_url}" | ||
) | ||
|
||
@api.depends("request_time", "response_time") | ||
def _compute_time(self): | ||
for log in self: | ||
if log.request_time and log.response_time: | ||
log.time = log.response_time - log.request_time | ||
else: | ||
log.time = 0 | ||
|
||
@api.depends("request_headers") | ||
def _compute_request_headers_derived(self): | ||
for log in self: | ||
headers = log.request_headers or {} | ||
log.request_content_type = headers.get("content-type", "") | ||
log.request_content_length = headers.get("content-length", 0) | ||
log.referrer = headers.get("referer", "") | ||
|
||
@api.depends("response_headers") | ||
def _compute_response_headers_derived(self): | ||
for log in self: | ||
headers = log.response_headers or {} | ||
log.response_content_type = headers.get("content-type", "") | ||
log.response_content_length = headers.get("content-length", 0) | ||
|
||
@api.depends("request_body") | ||
def _compute_request_preview(self): | ||
for log in self.with_context(bin_size=False): | ||
log.request_preview = log._body_preview(log.request_body) | ||
|
||
@api.depends("response_body") | ||
def _compute_response_preview(self): | ||
for log in self.with_context(bin_size=False): | ||
log.response_preview = log._body_preview(log.response_body) | ||
|
||
def _body_preview(self, body): | ||
# Display the first 1000 characters of the body if it's a text content | ||
body_preview = False | ||
if body: | ||
try: | ||
body_preview = body.decode("utf-8", errors="ignore") | ||
if len(body_preview) > 1000: | ||
body_preview = body_preview[:1000] + "...\n(...)" | ||
except UnicodeDecodeError: | ||
body_preview = False | ||
return body_preview | ||
|
||
@api.depends("request_headers", "response_headers") | ||
def _compute_headers_preview(self): | ||
for log in self: | ||
log.request_headers_preview = log._headers_preview(log.request_headers) | ||
log.response_headers_preview = log._headers_preview(log.response_headers) | ||
|
||
def _headers_preview(self, headers): | ||
return json.dumps(headers, sort_keys=True, indent=4) if headers else False | ||
|
||
@api.depends("request_body") | ||
def _compute_request_b64(self): | ||
for log in self: | ||
log.request_b64 = base64.b64encode(log.request_body or b"") | ||
|
||
@api.depends("response_body") | ||
def _compute_response_b64(self): | ||
for log in self: | ||
log.response_b64 = base64.b64encode(log.response_body or b"") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
- Florian Mounier <[email protected]> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
This module allows to store request and response logs for any API. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,8 +6,8 @@ | |
--> | ||
<odoo> | ||
|
||
<record id="group_fastapi_log" model="res.groups"> | ||
<field name="name">Fastapi Log Access</field> | ||
<record id="group_api_log" model="res.groups"> | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. question: (same as above) There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. See response for the question above. |
||
<field name="name">API Log Access</field> | ||
<field | ||
name="users" | ||
eval="[(4, ref('base.user_root')), (4, ref('base.user_admin'))]" | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
question: does this change require a migration?
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.
Since
fastapi_log
isn't merged yet, I wouldn't bother doing migrations in general.If we want to keep the user's edits on
fastapi_log
's record then a migration is needed, otherwise Odoo will remove the old record and create a new one; since this is not a record usually edited by the user I wouldn't do a migration.