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.

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