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.

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