Logging handler to send logs to your OpenSearch cluster with bulk SSL. Forked from https://github.com/logzio/logzio-python-handler
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.

129 lines
4.3 KiB

7 years ago
3 years ago
3 years ago
7 years ago
  1. import sys
  2. import json
  3. import logging
  4. import datetime
  5. import traceback
  6. import logging.handlers
  7. from .sender import LogzioSender
  8. from .exceptions import LogzioException
  9. class LogzioHandler(logging.Handler):
  10. def __init__(self,
  11. token,
  12. logzio_type="python",
  13. logs_drain_timeout=3,
  14. url="https://listener.logz.io:8071",
  15. debug=False,
  16. backup_logs=True,
  17. network_timeout=10.0,
  18. retries_no=4,
  19. retry_timeout=2,
  20. add_context=False):
  21. if not token:
  22. raise LogzioException('Logz.io Token must be provided')
  23. self.logzio_type = logzio_type
  24. if add_context:
  25. try:
  26. from opentelemetry.instrumentation.logging import LoggingInstrumentor
  27. LoggingInstrumentor().instrument(set_logging_format=True)
  28. except ImportError:
  29. print("""Can't add trace context.
  30. OpenTelemetry logging optional package isn't installed.
  31. Please install the following package:
  32. pip install 'logzio-python-handler[opentelemetry-logging]'""")
  33. self.logzio_sender = LogzioSender(
  34. token=token,
  35. url=url,
  36. logs_drain_timeout=logs_drain_timeout,
  37. debug=debug,
  38. backup_logs=backup_logs,
  39. network_timeout=network_timeout,
  40. number_of_retries=retries_no,
  41. retry_timeout=retry_timeout)
  42. logging.Handler.__init__(self)
  43. def __del__(self):
  44. del self.logzio_sender
  45. def extra_fields(self, message):
  46. not_allowed_keys = (
  47. 'args', 'asctime', 'created', 'exc_info', 'stack_info', 'exc_text',
  48. 'filename', 'funcName', 'levelname', 'levelno', 'lineno', 'module',
  49. 'msecs', 'msecs', 'message', 'msg', 'name', 'pathname', 'process',
  50. 'processName', 'relativeCreated', 'thread', 'threadName')
  51. if sys.version_info < (3, 0):
  52. # long and basestring don't exist in py3 so, NOQA
  53. var_type = (basestring, bool, dict, float, # NOQA
  54. int, long, list, type(None)) # NOQA
  55. else:
  56. var_type = (str, bool, dict, float, int, list, type(None))
  57. extra_fields = {}
  58. for key, value in message.__dict__.items():
  59. if key not in not_allowed_keys:
  60. if isinstance(value, var_type):
  61. extra_fields[key] = value
  62. else:
  63. extra_fields[key] = repr(value)
  64. return extra_fields
  65. def flush(self):
  66. self.logzio_sender.flush()
  67. def format(self, record):
  68. message = super(LogzioHandler, self).format(record)
  69. try:
  70. if record.exc_info:
  71. message = message.split("\n")[0] # only keep the original formatted message part
  72. return json.loads(message)
  73. except (TypeError, ValueError):
  74. return message
  75. def format_exception(self, exc_info):
  76. return '\n'.join(traceback.format_exception(*exc_info))
  77. def format_message(self, message):
  78. now = datetime.datetime.utcnow()
  79. timestamp = now.strftime('%Y-%m-%dT%H:%M:%S') + \
  80. '.%03d' % (now.microsecond / 1000) + 'Z'
  81. return_json = {
  82. 'logger': message.name,
  83. 'line_number': message.lineno,
  84. 'path_name': message.pathname,
  85. 'log_level': message.levelname,
  86. 'type': self.logzio_type,
  87. 'message': message.getMessage(),
  88. '@timestamp': timestamp
  89. }
  90. if message.exc_info:
  91. return_json['exception'] = self.format_exception(message.exc_info)
  92. # # We want to ignore default logging formatting on exceptions
  93. # # As we handle those differently directly into exception field
  94. formatted_message = self.format(message)
  95. # Exception with multiple fields, apply them to log json.
  96. if isinstance(formatted_message, dict):
  97. return_json.update(formatted_message)
  98. # No exception, apply default formatted message
  99. elif not message.exc_info:
  100. return_json['message'] = formatted_message
  101. return_json.update(self.extra_fields(message))
  102. return return_json
  103. def emit(self, record):
  104. self.logzio_sender.append(self.format_message(record))