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.

161 lines
5.6 KiB

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