You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

88 lines
2.4 KiB

  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. "taskName",
  45. "thread",
  46. "threadName",
  47. }
  48. class JsonFormatter(logging.Formatter):
  49. def format(self, record: logging.LogRecord) -> str:
  50. event = {
  51. "log": record.getMessage(),
  52. "namespace": record.name,
  53. "level": record.levelname,
  54. }
  55. return self._format(record, event)
  56. def _format(self, record: logging.LogRecord, event: dict) -> str:
  57. # Add attributes specified via the extra keyword to the logged event.
  58. for key, value in record.__dict__.items():
  59. if key not in _IGNORED_LOG_RECORD_ATTRIBUTES:
  60. event[key] = value
  61. if record.exc_info:
  62. exc_type, exc_value, _ = record.exc_info
  63. if exc_type:
  64. event["exc_type"] = f"{exc_type.__name__}"
  65. event["exc_value"] = f"{exc_value}"
  66. return _encoder.encode(event)
  67. class TerseJsonFormatter(JsonFormatter):
  68. def format(self, record: logging.LogRecord) -> str:
  69. event = {
  70. "log": record.getMessage(),
  71. "namespace": record.name,
  72. "level": record.levelname,
  73. "time": round(record.created, 2),
  74. }
  75. return self._format(record, event)