Skip to content

Commit

Permalink
Restore formatters
Browse files Browse the repository at this point in the history
  • Loading branch information
neob91-close committed Dec 13, 2024
1 parent 8daf26f commit f2f1059
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions inbox/api/wsgi.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import logging
import sys

import json_log_formatter
from gunicorn.workers.gthread import ThreadWorker

from inbox.error_handling import maybe_enable_rollbar
Expand All @@ -26,4 +28,58 @@ def init_process(self) -> None:
LOGLEVEL = config.get("LOGLEVEL", 10)


class JsonRequestFormatter(json_log_formatter.JSONFormatter):
"""
Custom JSON log formatter for gunicorn access logs.
Adapted from https://til.codeinthehole.com/posts/how-to-get-gunicorn-to-log-as-json/
"""

def json_record(
self,
message: str,
extra: "dict[str, str | int | float]",
record: logging.LogRecord,
) -> "dict[str, str | int | float]":
# Convert the log record to a JSON object.
# See https://docs.gunicorn.org/en/stable/settings.html#access-log-format

url = record.args["U"]
if record.args["q"]:
url += f"?{record.args['q']}"

method = record.args["m"]
log_context = record.args.get("{log_context}e", {})

return dict(
response_bytes=record.args["B"],
request_time=float(record.args["L"]),
remote_address=record.args["h"],
http_status=record.args["s"],
http_request=f"{method} {url}",
request_method=method,
**log_context,
)


class JsonErrorFormatter(json_log_formatter.JSONFormatter):
"""
Custom JSON log formatter for gunicorn error logs.
Adapted from https://til.codeinthehole.com/posts/how-to-get-gunicorn-to-log-as-json/
"""

def json_record(
self,
message: str,
extra: "dict[str, str | int | float]",
record: logging.LogRecord,
) -> "dict[str, str | int | float]":
payload: "dict[str, str | int | float]" = super().json_record(
message, extra, record
)
payload["level"] = record.levelname
return payload


__all__ = ["NylasWSGIWorker"]

0 comments on commit f2f1059

Please sign in to comment.