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.

347 lines
12 KiB

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