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.

184 lines
6.7 KiB

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