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.

354 lines
12 KiB

8 years ago
9 years ago
4 years ago
1 year ago
1 year 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. If you'd like to use [Trace context](https://github.com/logzio/logzio-python-handler#trace-context) then you need to install the OpenTelemetry logging instrumentation dependecy by running the following command:
  20. ```bash
  21. pip install logzio-python-handler[opentelemetry-logging]
  22. ```
  23. ## Tested Python Versions
  24. Travis CI will build this handler and test against:
  25. - "3.5"
  26. - "3.6"
  27. - "3.7"
  28. - "3.8"
  29. - "3.9"
  30. - "3.10"
  31. - "3.11"
  32. We can't ensure compatibility to any other version, as we can't test it automatically.
  33. To run tests:
  34. ```bash
  35. $ pip install tox
  36. $ tox
  37. ...
  38. ```
  39. ## Python configuration
  40. #### Config File
  41. ```python
  42. [handlers]
  43. keys=LogzioHandler
  44. [handler_LogzioHandler]
  45. class=logzio.handler.LogzioHandler
  46. formatter=logzioFormat
  47. args=('token', 'my_type')
  48. [formatters]
  49. keys=logzioFormat
  50. [loggers]
  51. keys=root
  52. [logger_root]
  53. handlers=LogzioHandler
  54. level=INFO
  55. [formatter_logzioFormat]
  56. format={"additional_field": "value"}
  57. ```
  58. *args=() arguments, by order*
  59. - Your logz.io token
  60. - Log type, for searching in logz.io (defaults to "python")
  61. - Time to sleep between draining attempts (defaults to "3")
  62. - Logz.io Listener address (defaults to "https://listener.logz.io:8071")
  63. - Debug flag. Set to True, will print debug messages to stdout. (defaults to "False")
  64. - Backup logs flag. Set to False, will disable the local backup of logs in case of failure. (defaults to "True")
  65. - Network timeout, in seconds, int or float, for sending the logs to logz.io. (defaults to 10)
  66. - Retries number (retry_no, defaults to 4).
  67. - Retry timeout (retry_timeout) in seconds (defaults to 2).
  68. Please note, that you have to configure those parameters by this exact order.
  69. i.e. you cannot set Debug to true, without configuring all of the previous parameters as well.
  70. #### Dict Config
  71. ```python
  72. LOGGING = {
  73. 'version': 1,
  74. 'disable_existing_loggers': False,
  75. 'formatters': {
  76. 'logzioFormat': {
  77. 'format': '{"additional_field": "value"}',
  78. 'validate': False
  79. }
  80. },
  81. 'handlers': {
  82. 'logzio': {
  83. 'class': 'logzio.handler.LogzioHandler',
  84. 'level': 'INFO',
  85. 'formatter': 'logzioFormat',
  86. 'token': '<<LOGZIO-TOKEN>>',
  87. 'logzio_type': 'python-handler',
  88. 'logs_drain_timeout': 5,
  89. 'url': 'https://<<LOGZIO-URL>>:8071',
  90. 'retries_no': 4,
  91. 'retry_timeout': 2,
  92. }
  93. },
  94. 'loggers': {
  95. '': {
  96. 'level': 'DEBUG',
  97. 'handlers': ['logzio'],
  98. 'propagate': True
  99. }
  100. }
  101. }
  102. ```
  103. Replace:
  104. * <<LOGZIO-TOKEN>> - your logz.io account token.
  105. * <<LOGZIO-URL>> - logz.io url, as described [here](https://docs.logz.io/user-guide/accounts/account-region.html#regions-and-urls).
  106. #### Serverless platforms
  107. 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.
  108. **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.
  109. #### Code Example
  110. ```python
  111. import logging
  112. import logging.config
  113. # If you're using a serverless function, uncomment.
  114. # from logzio.flusher import LogzioFlusher
  115. # Say I have saved my dictionary configuration in a variable named 'LOGGING' - see 'Dict Config' sample section
  116. logging.config.dictConfig(LOGGING)
  117. logger = logging.getLogger('superAwesomeLogzioLogger')
  118. # If you're using a serverless function, uncomment.
  119. # @LogzioFlusher(logger)
  120. def my_func():
  121. logger.info('Test log')
  122. logger.warn('Warning')
  123. try:
  124. 1/0
  125. except:
  126. logger.exception("Supporting exceptions too!")
  127. ```
  128. #### Extra Fields
  129. In case you need to dynamic metadata to your logger, other then the constant metadata from the formatter, you can use the "extra" parameter.
  130. All key values in the dictionary passed in "extra" will be presented in Logz.io as new fields in the log you are sending.
  131. Please note, that you cannot override default fields by the python logger (i.e. lineno, thread, etc..)
  132. For example:
  133. ```python
  134. logger.info('Warning', extra={'extra_key':'extra_value'})
  135. ```
  136. #### Dynamic Extra Fields
  137. If you prefer, you can add extra fields to your logs dynamically, and not pre-defining them in the configuration.
  138. This way, you can allow different logs to have different extra fields.
  139. See the following code example:
  140. ```python
  141. from logzio.handler import ExtraFieldsLogFilter
  142. def main():
  143. logger.info("Test log") # Outputs: {"message":"Test log"}
  144. extra_fields = {"foo":"bar","counter":1}
  145. logger.addFilter(ExtraFieldsLogFilter(extra_fields))
  146. logger.warning("Warning test log") # Outputs: {"message":"Warning test log","foo":"bar","counter":1}
  147. error_fields = {"err_msg":"Failed to run due to exception.","status_code":500}
  148. logger.addFilter(ExtraFieldsLogFilter(error_fields))
  149. logger.error("Error test log") # Outputs: {"message":"Error test log","foo":"bar","counter":1,"err_msg":"Failed to run due to exception.","status_code":500}
  150. # If you'd like to remove filters from future logs using the logger.removeFilter option:
  151. logger.removeFilter(ExtraFieldsLogFilter(error_fields))
  152. logger.debug("Debug test log") # Outputs: {"message":"Debug test log","foo":"bar","counter":1}
  153. ```
  154. ## Django configuration
  155. ```python
  156. LOGGING = {
  157. 'version': 1,
  158. 'disable_existing_loggers': False,
  159. 'formatters': {
  160. 'verbose': {
  161. 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
  162. },
  163. 'logzioFormat': {
  164. 'format': '{"additional_field": "value"}'
  165. }
  166. },
  167. 'handlers': {
  168. 'console': {
  169. 'class': 'logging.StreamHandler',
  170. 'level': 'DEBUG',
  171. 'formatter': 'verbose'
  172. },
  173. 'logzio': {
  174. 'class': 'logzio.handler.LogzioHandler',
  175. 'level': 'INFO',
  176. 'formatter': 'logzioFormat',
  177. 'token': 'token',
  178. 'logzio_type': "django",
  179. 'logs_drain_timeout': 5,
  180. 'url': 'https://listener.logz.io:8071',
  181. 'debug': True,
  182. 'network_timeout': 10,
  183. },
  184. },
  185. 'loggers': {
  186. 'django': {
  187. 'handlers': ['console', ],
  188. 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO')
  189. },
  190. 'appname': {
  191. 'handlers': ['console', 'logzio'],
  192. 'level': 'INFO'
  193. }
  194. }
  195. }
  196. ```
  197. *Change*
  198. - token - Your logzio token
  199. - url - Logz.io Listener address
  200. - logs_drain_count - Number of logs to keep in buffer before draining
  201. - logs_drain_timeout - Time to wait before draining, regardless of the previouse setting
  202. - logzio_type - Log type, for searching in logz.io (defaults to "python"), it cannot contain a space.
  203. - appname - Your django app
  204. ## Trace context
  205. If you're sending traces with OpenTelemetry instrumentation (auto or manual), you can correlate your logs with the trace context.
  206. That way, your logs will have traces data in it, such as service name, span id and trace id.
  207. Make sure to install the OpenTelemetry logging instrumentation dependecy by running the following command:
  208. ```bash
  209. pip install logzio-python-handler[opentelemetry-logging]
  210. ```
  211. To enable this feature, set the `add_context` param in your handler configuration to `True`, like in this example:
  212. ```python
  213. LOGGING = {
  214. 'version': 1,
  215. 'disable_existing_loggers': False,
  216. 'formatters': {
  217. 'logzioFormat': {
  218. 'format': '{"additional_field": "value"}',
  219. 'validate': False
  220. }
  221. },
  222. 'handlers': {
  223. 'logzio': {
  224. 'class': 'logzio.handler.LogzioHandler',
  225. 'level': 'INFO',
  226. 'formatter': 'logzioFormat',
  227. 'token': '<<LOGZIO-TOKEN>>',
  228. 'logzio_type': 'python-handler',
  229. 'logs_drain_timeout': 5,
  230. 'url': 'https://<<LOGZIO-URL>>:8071',
  231. 'retries_no': 4,
  232. 'retry_timeout': 2,
  233. 'add_context': True
  234. }
  235. },
  236. 'loggers': {
  237. '': {
  238. 'level': 'DEBUG',
  239. 'handlers': ['logzio'],
  240. 'propagate': True
  241. }
  242. }
  243. }
  244. ```
  245. 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).
  246. ## Release Notes
  247. - 4.1.0
  248. - Add ability to dynamically attach extra fields to the logs.
  249. - Import opentelemetry logging dependency only if trace context is enabled and dependency is installed manually.
  250. - Updated `opentelemetry-instrumentation-logging==0.39b0`
  251. - Updated `setuptools>=68.0.0`
  252. - Added tests for Python versions: 3.9, 3.10, 3.11
  253. - 4.0.2
  254. - Fix bug for logging exceptions ([#76](https://github.com/logzio/logzio-python-handler/pull/76))
  255. - 4.0.1
  256. - Updated `protobuf>=3.20.2`.
  257. - Added dependency `setuptools>=65.5.1`
  258. - 4.0.0
  259. - Add ability to automatically attach trace context to the logs.
  260. <details>
  261. <summary markdown="span"> Expand to check old versions </summary>
  262. - 3.1.1
  263. - Bug fixes (issue #68, exception message formatting)
  264. - Added CI: Tests and Auto release
  265. - 3.1.0
  266. - Bug fixes
  267. - Retry number and timeout is now configurable
  268. - 3.0.0
  269. - Deprecated `python2.7` & `python3.4`
  270. - Changed log levels on `_flush_queue()` method (@hilsenrat)
  271. - 2.0.15
  272. - Added flusher decorator for serverless platforms(@mcmasty)
  273. - Add support for `python3.7` and `python3.8`
  274. - 2.0.13
  275. - Add support for `pypy` and `pypy3`(@rudaporto-olx)
  276. - Add timeout for requests.post() (@oseemann)
  277. - 2.0.12 - Support disable logs local backup
  278. - 2.0.11 - Completely isolate exception from the message
  279. - 2.0.10 - Not ignoring formatting on exceptions
  280. - 2.0.9 - Support extra fields on exceptions too (Thanks @asafc64!)
  281. - 2.0.8 - Various PEP8, testings and logging changes (Thanks @nir0s!)
  282. - 2.0.7 - Make sure sending thread is alive after fork (Thanks @jo-tham!)
  283. - 2.0.6 - Add "flush()" method to manually drain the queue (Thanks @orenmazor!)
  284. - 2.0.5 - Support for extra fields
  285. - 2.0.4 - Publish package as source along wheel, and supprt python3 packagin (Thanks @cchristous!)
  286. - 2.0.3 - Fix bug that consumed more logs while draining than Logz.io's bulk limit
  287. - 2.0.2 - Support for formatted messages (Thanks @johnraz!)
  288. - 2.0.1 - Added __all__ to __init__.py, so support * imports
  289. - 2.0.0 - Production, stable release.
  290. - *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.
  291. - 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.
  292. - Simplifications and Robustness
  293. - Full testing framework
  294. - 1.X - Beta versions
  295. </details>