Skip to content

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
wants to merge 5 commits into
base: 16.0-add-fastapi_log
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions api_log/README.rst
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.
1 change: 1 addition & 0 deletions api_log/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from . import models
20 changes: 20 additions & 0 deletions api_log/__manifest__.py
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"],
}
1 change: 1 addition & 0 deletions api_log/models/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from . import api_log
224 changes: 224 additions & 0 deletions api_log/models/api_log.py
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"")
1 change: 1 addition & 0 deletions api_log/readme/CONTRIBUTORS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Florian Mounier <[email protected]>
1 change: 1 addition & 0 deletions api_log/readme/DESCRIPTION.md
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.
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
-->
<odoo>
<record id="access_fastapi_log" model="ir.model.access">
<field name="name">Fastapi Log: Read access</field>
<field name="model_id" ref="model_fastapi_log" />
<field name="group_id" ref="group_fastapi_log" />
<record id="access_api_log" model="ir.model.access">

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?

Copy link
Author

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.

<field name="name">API Log: Read access</field>
<field name="model_id" ref="model_api_log" />
<field name="group_id" ref="group_api_log" />
<field name="perm_read" eval="True" />
<field name="perm_write" eval="False" />
<field name="perm_create" eval="False" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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">

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: (same as above)

Copy link
Author

Choose a reason for hiding this comment

The 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'))]"
Expand Down
Loading