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.

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