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.

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