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.

133 lines
5.1 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._initialize_sending_thread()
  29. def _initialize_sending_thread(self):
  30. self.sending_thread = Thread(target=self._drain_queue)
  31. self.sending_thread.daemon = False
  32. self.sending_thread.name = "logzio-sending-thread"
  33. self.sending_thread.start()
  34. def append(self, logs_message):
  35. # Queue lib is thread safe, no issue here
  36. if not self.sending_thread.is_alive():
  37. self._initialize_sending_thread()
  38. self.queue.put(json.dumps(logs_message))
  39. def flush(self):
  40. self._flush_queue()
  41. def _debug(self, message):
  42. if self.debug:
  43. print(str(message))
  44. def _drain_queue(self):
  45. last_try = False
  46. while not last_try:
  47. # If main is exited, we should run one last time and try to remove all logs
  48. if not self.is_main_thread_active():
  49. self._debug("Identified quit of main thread, sending logs one last time")
  50. last_try = True
  51. try:
  52. self._flush_queue()
  53. except Exception as e:
  54. self._debug("Unexpected exception while draining queue to Logz.io, swallowing. Exception: " + str(e))
  55. if not last_try:
  56. sleep(self.logs_drain_timeout)
  57. def _flush_queue(self):
  58. # Sending logs until queue is empty
  59. while not self.queue.empty():
  60. logs_list = self._get_messages_up_to_max_allowed_size()
  61. self._debug("Starting to drain " + str(len(logs_list)) + " logs to Logz.io")
  62. # Not configurable from the outside
  63. sleep_between_retries = 2
  64. number_of_retries = 4
  65. should_backup_to_disk = True
  66. headers = {"Content-type": "text/plain"}
  67. for current_try in range(number_of_retries):
  68. should_retry = False
  69. try:
  70. response = requests.post(self.url, headers=headers, data='\n'.join(logs_list))
  71. if response.status_code != 200:
  72. if response.status_code == 400:
  73. 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))
  74. should_backup_to_disk = False
  75. break
  76. if response.status_code == 401:
  77. print("You are not authorized with Logz.io! Token OK? dropping logs...")
  78. should_backup_to_disk = False
  79. break
  80. else:
  81. print("Got {} while sending logs to Logz.io, Try ({}/{}). Response: {}".format(response.status_code, current_try + 1, number_of_retries, response.text))
  82. should_retry = True
  83. else:
  84. self._debug("Successfully sent bulk of " + str(len(logs_list)) + " logs to Logz.io!")
  85. should_backup_to_disk = False
  86. break
  87. except Exception as e:
  88. print("Got exception while sending logs to Logz.io, Try ({}/{}). Message: {}".format(current_try + 1, number_of_retries, e))
  89. should_retry = True
  90. if should_retry:
  91. sleep(sleep_between_retries)
  92. sleep_between_retries *= 2
  93. if should_backup_to_disk:
  94. # Write to file
  95. print("Could not send logs to Logz.io after " + str(number_of_retries) + " tries, backing up to local file system.")
  96. backup_logs(logs_list)
  97. def _get_messages_up_to_max_allowed_size(self):
  98. logs_list = []
  99. current_size = 0
  100. while not self.queue.empty():
  101. current_log = self.queue.get()
  102. current_size += sys.getsizeof(current_log)
  103. logs_list.append(current_log)
  104. if current_size >= MAX_BULK_SIZE_IN_BYTES:
  105. break
  106. return logs_list