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.

110 lines
3.4 KiB

7 years ago
7 years ago
7 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. if not token:
  18. raise LogzioException('Logz.io Token must be provided')
  19. self.logzio_type = logzio_type
  20. self.logzio_sender = LogzioSender(
  21. token=token,
  22. url=url,
  23. logs_drain_timeout=logs_drain_timeout,
  24. debug=debug,
  25. backup_logs=backup_logs)
  26. logging.Handler.__init__(self)
  27. def __del__(self):
  28. del self.logzio_sender
  29. def extra_fields(self, message):
  30. not_allowed_keys = (
  31. 'args', 'asctime', 'created', 'exc_info', 'stack_info', 'exc_text',
  32. 'filename', 'funcName', 'levelname', 'levelno', 'lineno', 'module',
  33. 'msecs', 'msecs', 'message', 'msg', 'name', 'pathname', 'process',
  34. 'processName', 'relativeCreated', 'thread', 'threadName')
  35. if sys.version_info < (3, 0):
  36. # long and basestring don't exist in py3 so, NOQA
  37. var_type = (basestring, bool, dict, float, # NOQA
  38. int, long, list, type(None)) # NOQA
  39. else:
  40. var_type = (str, bool, dict, float, int, list, type(None))
  41. extra_fields = {}
  42. for key, value in message.__dict__.items():
  43. if key not in not_allowed_keys:
  44. if isinstance(value, var_type):
  45. extra_fields[key] = value
  46. else:
  47. extra_fields[key] = repr(value)
  48. return extra_fields
  49. def flush(self):
  50. self.logzio_sender.flush()
  51. def format(self, record):
  52. message = super(LogzioHandler, self).format(record)
  53. try:
  54. return json.loads(message)
  55. except (TypeError, ValueError):
  56. return message
  57. def format_exception(self, exc_info):
  58. return '\n'.join(traceback.format_exception(*exc_info))
  59. def format_message(self, message):
  60. now = datetime.datetime.utcnow()
  61. timestamp = now.strftime('%Y-%m-%dT%H:%M:%S') + \
  62. '.%03d' % (now.microsecond / 1000) + 'Z'
  63. return_json = {
  64. 'logger': message.name,
  65. 'line_number': message.lineno,
  66. 'path_name': message.pathname,
  67. 'log_level': message.levelname,
  68. 'type': self.logzio_type,
  69. 'message': message.getMessage(),
  70. '@timestamp': timestamp
  71. }
  72. if message.exc_info:
  73. return_json['exception'] = self.format_exception(message.exc_info)
  74. # We want to ignore default logging formatting on exceptions
  75. # As we handle those differently directly into exception field
  76. message.exc_info = None
  77. message.exc_text = None
  78. formatted_message = self.format(message)
  79. if isinstance(formatted_message, dict):
  80. return_json.update(formatted_message)
  81. else:
  82. return_json['message'] = formatted_message
  83. return_json.update(self.extra_fields(message))
  84. return return_json
  85. def emit(self, record):
  86. self.logzio_sender.append(self.format_message(record))