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.

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