Skip to content

Commit

Permalink
Add JSON log formatter
Browse files Browse the repository at this point in the history
  • Loading branch information
lalinsky committed Feb 23, 2024
1 parent 4612660 commit fcebc03
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 6 deletions.
42 changes: 42 additions & 0 deletions acoustid/gunicorn_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
logconfig_dict = {
"version": 1,
"disable_existing_loggers": True,
"root": {"level": "INFO", "handlers": ["error_console"]},
"loggers": {
"gunicorn.error": {
"level": "INFO",
"handlers": ["error_console"],
"propagate": False,
"qualname": "gunicorn.error"
},

"gunicorn.access": {
"level": "INFO",
"handlers": ["console"],
"propagate": False,
"qualname": "gunicorn.access"
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "generic",
"stream": "ext://sys.stdout"
},
"error_console": {
"class": "logging.StreamHandler",
"formatter": "json",
"stream": "ext://sys.stderr"
},
},
'formatters': {
'json': {
'class': 'acoustid.logging.JsonLogFormatter',
},
"generic": {
"format": "%(asctime)s [%(process)d] [%(levelname)s] %(message)s",
"datefmt": "[%Y-%m-%d %H:%M:%S %z]",
"class": "logging.Formatter"
}
},
}
23 changes: 23 additions & 0 deletions acoustid/logging.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import logging
import datetime
import json


DEFAULT_LOG_RECORD_KEYS = set(logging.makeLogRecord({}).__dict__.keys())


class JsonLogFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
message = {
"time": datetime.datetime.fromtimestamp(record.created).astimezone().isoformat(timespec='milliseconds'),
"level": record.levelname.lower(),
"message": record.getMessage(),
}
if record.exc_info:
message["exception"] = self.formatException(record.exc_info)
for key, value in record.__dict__.items():
if key not in message:
if key not in DEFAULT_LOG_RECORD_KEYS:
message[key] = value
return json.dumps(message)

8 changes: 2 additions & 6 deletions acoustid/script.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from acoustid.db import DatabaseContext
from acoustid.fpstore import FpstoreClient
from acoustid.indexclient import IndexClientPool
from acoustid.logging import JsonLogFormatter

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -116,12 +117,7 @@ def setup_console_logging(self, quiet: bool = False, verbose: bool = False) -> N
if self._console_logging_configured:
return
handler = logging.StreamHandler()
handler.setFormatter(
logging.Formatter(
"[%(asctime)s] [%(process)s] [%(levelname)s] %(message)s",
"%Y-%m-%d %H:%M:%S %z",
)
)
handler.setFormatter(JsonLogFormatter())
if verbose:
handler.setLevel(logging.DEBUG)
if quiet:
Expand Down
2 changes: 2 additions & 0 deletions acoustid/wsgi_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ def run_api_app(config, workers=None, threads=None):
]
if config.statsd.enabled:
args.extend(["--statsd-prefix", "{}service.api".format(config.statsd.prefix)])
args.extend(["--config", "python:acoustid.gunicorn_config"])
return run_gunicorn(config, args)


Expand All @@ -158,4 +159,5 @@ def run_web_app(config, workers=None, threads=None):
]
if config.statsd.enabled:
args.extend(["--statsd-prefix", "{}service.web".format(config.statsd.prefix)])
args.extend(["--config", "python:acoustid.gunicorn_config"])
return run_gunicorn(config, args)

0 comments on commit fcebc03

Please sign in to comment.