_terse_json.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # Copyright 2019 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. Log formatters that output terse JSON.
  16. """
  17. import json
  18. import logging
  19. _encoder = json.JSONEncoder(ensure_ascii=False, separators=(",", ":"))
  20. # The properties of a standard LogRecord that should be ignored when generating
  21. # JSON logs.
  22. _IGNORED_LOG_RECORD_ATTRIBUTES = {
  23. "args",
  24. "asctime",
  25. "created",
  26. "exc_info",
  27. # exc_text isn't a public attribute, but is used to cache the result of formatException.
  28. "exc_text",
  29. "filename",
  30. "funcName",
  31. "levelname",
  32. "levelno",
  33. "lineno",
  34. "message",
  35. "module",
  36. "msecs",
  37. "msg",
  38. "name",
  39. "pathname",
  40. "process",
  41. "processName",
  42. "relativeCreated",
  43. "stack_info",
  44. "thread",
  45. "threadName",
  46. }
  47. class JsonFormatter(logging.Formatter):
  48. def format(self, record: logging.LogRecord) -> str:
  49. event = {
  50. "log": record.getMessage(),
  51. "namespace": record.name,
  52. "level": record.levelname,
  53. }
  54. return self._format(record, event)
  55. def _format(self, record: logging.LogRecord, event: dict) -> str:
  56. # Add attributes specified via the extra keyword to the logged event.
  57. for key, value in record.__dict__.items():
  58. if key not in _IGNORED_LOG_RECORD_ATTRIBUTES:
  59. event[key] = value
  60. if record.exc_info:
  61. exc_type, exc_value, _ = record.exc_info
  62. if exc_type:
  63. event["exc_type"] = f"{exc_type.__name__}"
  64. event["exc_value"] = f"{exc_value}"
  65. return _encoder.encode(event)
  66. class TerseJsonFormatter(JsonFormatter):
  67. def format(self, record: logging.LogRecord) -> str:
  68. event = {
  69. "log": record.getMessage(),
  70. "namespace": record.name,
  71. "level": record.levelname,
  72. "time": round(record.created, 2),
  73. }
  74. return self._format(record, event)