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.

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