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.9 KiB

7 years ago
  1. # This class is responsible for handling all asynchronous Logz.io's communication
  2. import sys
  3. import requests
  4. import json
  5. from threading import Thread, enumerate
  6. from datetime import datetime
  7. from time import sleep
  8. if sys.version[0] == '2':
  9. import Queue as queue
  10. else:
  11. import queue as queue
  12. MAX_BULK_SIZE_IN_BYTES = 1 * 1024 * 1024 # 1 MB
  13. def backup_logs(logs):
  14. timestamp = datetime.now().strftime("%d%m%Y-%H%M%S")
  15. print("Backing up your logs to logzio-failures-{0}.txt".format(timestamp))
  16. with open("logzio-failures-{0}.txt".format(timestamp), "a") as f:
  17. f.writelines('\n'.join(logs))
  18. class LogzioSender:
  19. def __init__(self, token, url="https://listener.logz.io:8071", logs_drain_timeout=5, debug=False):
  20. self.token = token
  21. self.url = "{0}/?token={1}".format(url, token)
  22. self.logs_drain_timeout = logs_drain_timeout
  23. self.debug = debug
  24. # Function to see if the main thread is alive
  25. self.is_main_thread_active = lambda: any((i.name == "MainThread") and i.is_alive() for i in enumerate())
  26. # Create a queue to hold logs
  27. self.queue = queue.Queue()
  28. self.sending_thread = Thread(target=self._drain_queue)
  29. self.sending_thread.daemon = False
  30. self.sending_thread.name = "logzio-sending-thread"
  31. self.sending_thread.start()
  32. def append(self, logs_message):
  33. # Queue lib is thread safe, no issue here
  34. self.queue.put(json.dumps(logs_message))
  35. def flush(self):
  36. self._flush_queue()
  37. def _debug(self, message):
  38. if self.debug:
  39. print(str(message))
  40. def _drain_queue(self):
  41. last_try = False
  42. while not last_try:
  43. # If main is exited, we should run one last time and try to remove all logs
  44. if not self.is_main_thread_active():
  45. self._debug("Identified quit of main thread, sending logs one last time")
  46. last_try = True
  47. try:
  48. self._flush_queue()
  49. except Exception as e:
  50. self._debug("Unexpected exception while draining queue to Logz.io, swallowing. Exception: " + str(e))
  51. if not last_try:
  52. sleep(self.logs_drain_timeout)
  53. def _flush_queue(self):
  54. # Sending logs until queue is empty
  55. while not self.queue.empty():
  56. logs_list = self._get_messages_up_to_max_allowed_size()
  57. self._debug("Starting to drain " + str(len(logs_list)) + " logs to Logz.io")
  58. # Not configurable from the outside
  59. sleep_between_retries = 2
  60. number_of_retries = 4
  61. should_backup_to_disk = True
  62. headers = {"Content-type": "text/plain"}
  63. for current_try in range(number_of_retries):
  64. should_retry = False
  65. try:
  66. response = requests.post(self.url, headers=headers, data='\n'.join(logs_list))
  67. if response.status_code != 200:
  68. if response.status_code == 400:
  69. print("Got 400 code from Logz.io. This means that some of your logs are too big, or badly formatted. response: {0}".format(response.text))
  70. should_backup_to_disk = False
  71. break
  72. if response.status_code == 401:
  73. print("You are not authorized with Logz.io! Token OK? dropping logs...")
  74. should_backup_to_disk = False
  75. break
  76. else:
  77. print("Got {} while sending logs to Logz.io, Try ({}/{}). Response: {}".format(response.status_code, current_try + 1, number_of_retries, response.text))
  78. should_retry = True
  79. else:
  80. self._debug("Successfully sent bulk of " + str(len(logs_list)) + " logs to Logz.io!")
  81. should_backup_to_disk = False
  82. break
  83. except Exception as e:
  84. print("Got exception while sending logs to Logz.io, Try ({}/{}). Message: {}".format(current_try + 1, number_of_retries, e))
  85. should_retry = True
  86. if should_retry:
  87. sleep(sleep_between_retries)
  88. sleep_between_retries *= 2
  89. if should_backup_to_disk:
  90. # Write to file
  91. print("Could not send logs to Logz.io after " + str(number_of_retries) + " tries, backing up to local file system.")
  92. backup_logs(logs_list)
  93. def _get_messages_up_to_max_allowed_size(self):
  94. logs_list = []
  95. current_size = 0
  96. while not self.queue.empty():
  97. current_log = self.queue.get()
  98. current_size += sys.getsizeof(current_log)
  99. logs_list.append(current_log)
  100. if current_size >= MAX_BULK_SIZE_IN_BYTES:
  101. break
  102. return logs_list