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.

58 lines
1.8 KiB

  1. import datetime
  2. import json
  3. import logging
  4. import logging.handlers
  5. import traceback
  6. from .sender import LogzioSender
  7. class LogzioHandler(logging.Handler):
  8. def __init__(self, token, logzio_type="python", logs_drain_timeout=3,
  9. url="https://listener.logz.io:8071", debug=False):
  10. if token is "":
  11. raise Exception("Logz.io Token must be provided")
  12. self.logzio_type = logzio_type
  13. self.logzio_sender = LogzioSender(token=token, url=url, logs_drain_timeout=logs_drain_timeout, debug=debug)
  14. logging.Handler.__init__(self)
  15. def format(self, record):
  16. message = super(LogzioHandler, self).format(record)
  17. try:
  18. return json.loads(message)
  19. except (TypeError, ValueError):
  20. return message
  21. def format_exception(self, exc_info):
  22. return '\n'.join(traceback.format_exception(*exc_info))
  23. def format_message(self, message):
  24. now = datetime.datetime.utcnow()
  25. timestamp = now.strftime("%Y-%m-%dT%H:%M:%S") + ".%03d" % (now.microsecond / 1000) + "Z"
  26. return_json = {
  27. "logger": message.name,
  28. "line_number": message.lineno,
  29. "path_name": message.pathname,
  30. "log_level": message.levelname,
  31. "type": self.logzio_type,
  32. "message": message.getMessage(),
  33. "@timestamp": timestamp
  34. }
  35. if message.exc_info:
  36. return_json["exception"] = self.format_exception(message.exc_info)
  37. else:
  38. formatted_message = self.format(message)
  39. if isinstance(formatted_message, dict):
  40. return_json.update(formatted_message)
  41. else:
  42. return_json["message"] = formatted_message
  43. return return_json
  44. def emit(self, record):
  45. self.logzio_sender.append(self.format_message(record))