Skip to content

Commit

Permalink
add info in views logger (tests in progress)
Browse files Browse the repository at this point in the history
  • Loading branch information
vincentporte committed Feb 25, 2025
1 parent 07e2e97 commit 53bed82
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
5 changes: 3 additions & 2 deletions config/settings/base.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import os

from dotenv import load_dotenv
from json_log_formatter import JSONFormatter
from machina import MACHINA_MAIN_STATIC_DIR, MACHINA_MAIN_TEMPLATE_DIR

from lacommunaute.utils.loggers import CustomJsonFormatter


load_dotenv()

Expand Down Expand Up @@ -312,7 +313,7 @@
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"json": {"()": JSONFormatter},
"json": {"()": CustomJsonFormatter},
},
"handlers": {
"console": {"class": "logging.StreamHandler", "formatter": "json"},
Expand Down
1 change: 1 addition & 0 deletions lacommunaute/forum_conversation/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ def form_valid(self, *args, **kwargs):
valid = super().form_valid(*args, **kwargs)

track_handler.mark_topic_read(self.forum_post.topic, self.request.user)
logger.info("form is valid", extra={"context": self})
return valid


Expand Down
19 changes: 19 additions & 0 deletions lacommunaute/utils/loggers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from json_log_formatter import JSONFormatter


class CustomJsonFormatter(JSONFormatter):
def json_record(self, message, extra, record):
extra["logger_name"] = record.name

if "context" in extra:
context = extra.pop("context")
if hasattr(context, "request"):
extra = extra | {
"view": context.request.resolver_match.view_name,
"kwargs": context.request.resolver_match.kwargs,
"method": context.request.method,
"user_id": context.request.user.id if context.request.user.is_authenticated else None,
"session_key": context.request.session.session_key,
}

return super().json_record(message, extra, record)

0 comments on commit 53bed82

Please sign in to comment.