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.

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