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.

253 lines
8.9 KiB

9 years ago
9 years ago
4 years ago
9 years ago
3 years ago
7 years ago
7 years ago
7 years ago
8 years ago
8 years ago
8 years ago
3 years ago
  1. [![PyPI version](https://badge.fury.io/py/logzio-python-handler.svg)](https://badge.fury.io/py/logzio-python-handler) [![Build Status](https://travis-ci.org/logzio/logzio-python-handler.svg?branch=master)](https://travis-ci.org/logzio/logzio-python-handler)
  2. # The Logz.io Python Handler
  3. <table><tr><th>
  4. ### Deprecation announcement
  5. Version 3.0.0 of this project ends support for Python 2.7, 3.3, and 3.4. We recommend migrating your projects to Python 3.5 or newer as soon as possible. We'll be happy to answer any questions you have in [a GitHub issue](https://github.com/logzio/logzio-python-handler/issues).
  6. Thanks! <br>
  7. The Logz.io Integrations team
  8. </th></tr></table>
  9. This is a Python handler that sends logs in bulk over HTTPS to Logz.io.
  10. The handler uses a subclass named LogzioSender (which can be used without this handler as well, to ship raw data).
  11. The LogzioSender class opens a new Thread, that consumes from the logs queue. Each iteration (its frequency of which can be configured by the logs_drain_timeout parameter), will try to consume the queue in its entirety.
  12. Logs will get divided into separate bulks, based on their size.
  13. LogzioSender will check if the main thread is alive. In case the main thread quits, it will try to consume the queue one last time, and then exit. So your program can hang for a few seconds, until the logs are drained.
  14. In case the logs failed to be sent to Logz.io after a couple of tries, they will be written to the local file system. You can later upload them to Logz.io using curl.
  15. ## Installation
  16. ```bash
  17. pip install logzio-python-handler
  18. ```
  19. ## Tested Python Versions
  20. Travis CI will build this handler and test against:
  21. - "3.5"
  22. - "3.6"
  23. - "3.7"
  24. - "3.8"
  25. We can't ensure compatibility to any other version, as we can't test it automatically.
  26. To run tests:
  27. ```bash
  28. $ pip install tox
  29. $ tox
  30. ...
  31. ```
  32. ## Python configuration
  33. #### Config File
  34. ```
  35. [handlers]
  36. keys=LogzioHandler
  37. [handler_LogzioHandler]
  38. class=logzio.handler.LogzioHandler
  39. formatter=logzioFormat
  40. args=('token', 'my_type')
  41. [formatters]
  42. keys=logzioFormat
  43. [loggers]
  44. keys=root
  45. [logger_root]
  46. handlers=LogzioHandler
  47. level=INFO
  48. [formatter_logzioFormat]
  49. format={"additional_field": "value"}
  50. ```
  51. *args=() arguments, by order*
  52. - Your logz.io token
  53. - Log type, for searching in logz.io (defaults to "python")
  54. - Time to sleep between draining attempts (defaults to "3")
  55. - Logz.io Listener address (defaults to "https://listener.logz.io:8071")
  56. - Debug flag. Set to True, will print debug messages to stdout. (defaults to "False")
  57. - Backup logs flag. Set to False, will disable the local backup of logs in case of failure. (defaults to "True")
  58. - Network timeout, in seconds, int or float, for sending the logs to logz.io. (defaults to 10)
  59. - Retries number (retry_no), in seconds (defaults to 4).
  60. - Retry timeout (retry_timeout) in seconds (defaults to 2).
  61. Please note, that you have to configure those parameters by this exact order.
  62. i.e. you cannot set Debug to true, without configuring all of the previous parameters as well.
  63. #### Dict Config
  64. ```
  65. LOGGING = {
  66. 'version': 1,
  67. 'disable_existing_loggers': False,
  68. 'formatters': {
  69. 'logzioFormat': {
  70. 'format': '{"additional_field": "value"}',
  71. 'validate': False
  72. }
  73. },
  74. 'handlers': {
  75. 'logzio': {
  76. 'class': 'logzio.handler.LogzioHandler',
  77. 'level': 'INFO',
  78. 'formatter': 'logzioFormat',
  79. 'token': '<<LOGZIO-TOKEN>>',
  80. 'logs_drain_timeout': 5,
  81. 'url': 'https://<<LOGZIO-URL>>:8071',
  82. 'retries_no': 4,
  83. 'retry_timeout': 2,
  84. }
  85. },
  86. 'loggers': {
  87. '': {
  88. 'level': 'DEBUG',
  89. 'handlers': ['logzio'],
  90. 'propagate': True
  91. }
  92. }
  93. }
  94. ```
  95. Replace:
  96. * <<LOGZIO-TOKEN>> - your logz.io account token.
  97. * <<LOGZIO-URL>> - logz.io url, as described [here](https://docs.logz.io/user-guide/accounts/account-region.html#regions-and-urls).
  98. #### Serverless platforms
  99. If you're using a serverless function, you'll need to import and add the LogzioFlusher annotation before your sender function. To do this, in the code sample below, uncomment the `import` statement and the `@LogzioFlusher(logger)` annotation line.
  100. **Note:** For the LogzioFlusher to work properly, you'll need to make sure that the Logz.io. handler is added to the root logger. See the configuration above for an example.
  101. #### Code Example
  102. ```python
  103. import logging
  104. import logging.config
  105. # If you're using a serverless function, uncomment.
  106. # from logzio.flusher import LogzioFlusher
  107. # Say I have saved my dictionary configuration in a variable named 'LOGGING' - see 'Dict Config' sample section
  108. logging.config.dictConfig(LOGGING)
  109. logger = logging.getLogger('superAwesomeLogzioLogger')
  110. # If you're using a serverless function, uncomment.
  111. # @LogzioFlusher(logger)
  112. def my_func():
  113. logger.info('Test log')
  114. logger.warn('Warning')
  115. try:
  116. 1/0
  117. except:
  118. logger.exception("Supporting exceptions too!")
  119. ```
  120. #### Extra Fields
  121. In case you need to dynamic metadata to your logger, other then the constant metadata from the formatter, you can use the "extra" parameter.
  122. All key values in the dictionary passed in "extra" will be presented in Logz.io as new fields in the log you are sending.
  123. Please note, that you cannot override default fields by the python logger (i.e. lineno, thread, etc..)
  124. For example:
  125. ```
  126. logger.info('Warning', extra={'extra_key':'extra_value'})
  127. ```
  128. ## Django configuration
  129. ```
  130. LOGGING = {
  131. 'version': 1,
  132. 'disable_existing_loggers': False,
  133. 'formatters': {
  134. 'verbose': {
  135. 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
  136. },
  137. 'logzioFormat': {
  138. 'format': '{"additional_field": "value"}'
  139. }
  140. },
  141. 'handlers': {
  142. 'console': {
  143. 'class': 'logging.StreamHandler',
  144. 'level': 'DEBUG',
  145. 'formatter': 'verbose'
  146. },
  147. 'logzio': {
  148. 'class': 'logzio.handler.LogzioHandler',
  149. 'level': 'INFO',
  150. 'formatter': 'logzioFormat',
  151. 'token': 'token',
  152. 'logzio_type': "django",
  153. 'logs_drain_timeout': 5,
  154. 'url': 'https://listener.logz.io:8071',
  155. 'debug': True,
  156. 'network_timeout': 10,
  157. },
  158. },
  159. 'loggers': {
  160. 'django': {
  161. 'handlers': ['console', ],
  162. 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO')
  163. },
  164. 'appname': {
  165. 'handlers': ['console', 'logzio'],
  166. 'level': 'INFO'
  167. }
  168. }
  169. }
  170. ```
  171. *Change*
  172. - token - Your logzio token
  173. - url - Logz.io Listener address
  174. - logs_drain_count - Number of logs to keep in buffer before draining
  175. - logs_drain_timeout - Time to wait before draining, regardless of the previouse setting
  176. - logzio_type - Log type, for searching in logz.io (defaults to "python"), it cannot contain a space.
  177. - appname - Your django app
  178. Please note that if you are using `python 3.8` it is preferred to use the `logging.config.dictConfig` method, as mentioned in [python's documentation](https://docs.python.org/3/library/logging.config.html#configuration-file-format).
  179. ## Release Notes
  180. - 3.1.0
  181. - Bug fixes
  182. - Retry number and timeout is now configurable
  183. - 3.0.0
  184. - Deprecated `python2.7` & `python3.4`
  185. - Changed log levels on `_flush_queue()` method (@hilsenrat)
  186. <details>
  187. <summary markdown="span"> Expand to check old versions </summary>
  188. - 2.0.15
  189. - Added flusher decorator for serverless platforms(@mcmasty)
  190. - Add support for `python3.7` and `python3.8`
  191. - 2.0.13
  192. - Add support for `pypy` and `pypy3`(@rudaporto-olx)
  193. - Add timeout for requests.post() (@oseemann)
  194. - 2.0.12 - Support disable logs local backup
  195. - 2.0.11 - Completely isolate exception from the message
  196. - 2.0.10 - Not ignoring formatting on exceptions
  197. - 2.0.9 - Support extra fields on exceptions too (Thanks @asafc64!)
  198. - 2.0.8 - Various PEP8, testings and logging changes (Thanks @nir0s!)
  199. - 2.0.7 - Make sure sending thread is alive after fork (Thanks @jo-tham!)
  200. - 2.0.6 - Add "flush()" method to manually drain the queue (Thanks @orenmazor!)
  201. - 2.0.5 - Support for extra fields
  202. - 2.0.4 - Publish package as source along wheel, and supprt python3 packagin (Thanks @cchristous!)
  203. - 2.0.3 - Fix bug that consumed more logs while draining than Logz.io's bulk limit
  204. - 2.0.2 - Support for formatted messages (Thanks @johnraz!)
  205. - 2.0.1 - Added __all__ to __init__.py, so support * imports
  206. - 2.0.0 - Production, stable release.
  207. - *BREAKING* - Configuration option logs_drain_count was removed, and the order of the parameters has changed for better simplicity. Please review the parameters section above.
  208. - Introducing the LogzioSender class, which is generic and can be used without the handler wrap to ship raw data to Logz.io. Just create a new instance of the class, and use the append() method.
  209. - Simplifications and Robustness
  210. - Full testing framework
  211. - 1.X - Beta versions
  212. </details>