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.

180 lines
6.3 KiB

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