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.

245 lines
8.6 KiB

8 years ago
9 years ago
4 years ago
8 years ago
3 years ago
7 years ago
7 years ago
7 years ago
7 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. Please note, that you have to configure those parameters by this exact order.
  60. i.e. you cannot set Debug to true, without configuring all of the previous parameters as well.
  61. #### Dict Config
  62. ```
  63. LOGGING = {
  64. 'version': 1,
  65. 'disable_existing_loggers': False,
  66. 'formatters': {
  67. 'logzioFormat': {
  68. 'format': '{"additional_field": "value"}',
  69. 'validate': False
  70. }
  71. },
  72. 'handlers': {
  73. 'logzio': {
  74. 'class': 'logzio.handler.LogzioHandler',
  75. 'level': 'INFO',
  76. 'formatter': 'logzioFormat',
  77. 'token': '<<LOGZIO-TOKEN>>',
  78. 'logs_drain_timeout': 5,
  79. 'url': 'https://<<LOGZIO-URL>>:8071'
  80. }
  81. },
  82. 'loggers': {
  83. '': {
  84. 'level': 'DEBUG',
  85. 'handlers': ['logzio'],
  86. 'propagate': True
  87. }
  88. }
  89. }
  90. ```
  91. Replace:
  92. * <<LOGZIO-TOKEN>> - your logz.io account token.
  93. * <<LOGZIO-URL>> - logz.io url, as described [here](https://docs.logz.io/user-guide/accounts/account-region.html#regions-and-urls).
  94. #### Serverless platforms
  95. 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.
  96. **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.
  97. #### Code Example
  98. ```python
  99. import logging
  100. import logging.config
  101. # If you're using a serverless function, uncomment.
  102. # from logzio.flusher import LogzioFlusher
  103. # Say I have saved my dictionary configuration in a variable named 'LOGGING' - see 'Dict Config' sample section
  104. logging.config.dictConfig(LOGGING)
  105. logger = logging.getLogger('superAwesomeLogzioLogger')
  106. # If you're using a serverless function, uncomment.
  107. # @LogzioFlusher(logger)
  108. def my_func():
  109. logger.info('Test log')
  110. logger.warn('Warning')
  111. try:
  112. 1/0
  113. except:
  114. logger.exception("Supporting exceptions too!")
  115. ```
  116. #### Extra Fields
  117. In case you need to dynamic metadata to your logger, other then the constant metadata from the formatter, you can use the "extra" parameter.
  118. All key values in the dictionary passed in "extra" will be presented in Logz.io as new fields in the log you are sending.
  119. Please note, that you cannot override default fields by the python logger (i.e. lineno, thread, etc..)
  120. For example:
  121. ```
  122. logger.info('Warning', extra={'extra_key':'extra_value'})
  123. ```
  124. ## Django configuration
  125. ```
  126. LOGGING = {
  127. 'version': 1,
  128. 'disable_existing_loggers': False,
  129. 'formatters': {
  130. 'verbose': {
  131. 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
  132. },
  133. 'logzioFormat': {
  134. 'format': '{"additional_field": "value"}'
  135. }
  136. },
  137. 'handlers': {
  138. 'console': {
  139. 'class': 'logging.StreamHandler',
  140. 'level': 'DEBUG',
  141. 'formatter': 'verbose'
  142. },
  143. 'logzio': {
  144. 'class': 'logzio.handler.LogzioHandler',
  145. 'level': 'INFO',
  146. 'formatter': 'logzioFormat',
  147. 'token': 'token',
  148. 'logzio_type': "django",
  149. 'logs_drain_timeout': 5,
  150. 'url': 'https://listener.logz.io:8071',
  151. 'debug': True,
  152. 'network_timeout': 10,
  153. },
  154. },
  155. 'loggers': {
  156. 'django': {
  157. 'handlers': ['console', ],
  158. 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO')
  159. },
  160. 'appname': {
  161. 'handlers': ['console', 'logzio'],
  162. 'level': 'INFO'
  163. }
  164. }
  165. }
  166. ```
  167. *Change*
  168. - token - Your logzio token
  169. - url - Logz.io Listener address
  170. - logs_drain_count - Number of logs to keep in buffer before draining
  171. - logs_drain_timeout - Time to wait before draining, regardless of the previouse setting
  172. - logzio_type - Log type, for searching in logz.io (defaults to "python"), it cannot contain a space.
  173. - appname - Your django app
  174. 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).
  175. ## Release Notes
  176. - 3.0.0
  177. - Deprecated `python2.7` & `python3.4`
  178. - Changed log levels on `_flush_queue()` method (@hilsenrat)
  179. - 2.0.15
  180. - Added flusher decorator for serverless platforms(@mcmasty)
  181. - Add support for `python3.7` and `python3.8`
  182. <details>
  183. <summary markdown="span"> Expand to check old versions </summary>
  184. - 2.0.13
  185. - Add support for `pypy` and `pypy3`(@rudaporto-olx)
  186. - Add timeout for requests.post() (@oseemann)
  187. - 2.0.12 - Support disable logs local backup
  188. - 2.0.11 - Completely isolate exception from the message
  189. - 2.0.10 - Not ignoring formatting on exceptions
  190. - 2.0.9 - Support extra fields on exceptions too (Thanks @asafc64!)
  191. - 2.0.8 - Various PEP8, testings and logging changes (Thanks @nir0s!)
  192. - 2.0.7 - Make sure sending thread is alive after fork (Thanks @jo-tham!)
  193. - 2.0.6 - Add "flush()" method to manually drain the queue (Thanks @orenmazor!)
  194. - 2.0.5 - Support for extra fields
  195. - 2.0.4 - Publish package as source along wheel, and supprt python3 packagin (Thanks @cchristous!)
  196. - 2.0.3 - Fix bug that consumed more logs while draining than Logz.io's bulk limit
  197. - 2.0.2 - Support for formatted messages (Thanks @johnraz!)
  198. - 2.0.1 - Added __all__ to __init__.py, so support * imports
  199. - 2.0.0 - Production, stable release.
  200. - *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.
  201. - 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.
  202. - Simplifications and Robustness
  203. - Full testing framework
  204. - 1.X - Beta versions
  205. </details>