Skip to content

Commit 60438b2

Browse files
authored
docs: how the client uses logging (#434)
1 parent 215eb88 commit 60438b2

15 files changed

+86
-39
lines changed

CHANGELOG.md

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
## 1.29.0 [unreleased]
22

33
### Breaking Changes
4-
1. [#433](https://github.com/influxdata/influxdb-client-python/pull/433): Rename `InvocableScripts` to `InvokableScripts`
4+
1. [#433](https://github.com/influxdata/influxdb-client-python/pull/433): Rename `InvocableScripts` to `InvokableScripts`
5+
6+
### Documentation
7+
1. [#434](https://github.com/influxdata/influxdb-client-python/pull/434): How the client uses [logging](https://docs.python.org/3/library/logging.html)
58

69
## 1.28.0 [2022-04-19]
710

README.rst

+45
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ InfluxDB 2.0 client features
8484
- `Nanosecond precision`_
8585
- `Delete data`_
8686
- `Handling Errors`_
87+
- `Logging`_
8788

8889
Installation
8990
------------
@@ -1516,6 +1517,50 @@ Client automatically follows HTTP redirects. The default redirect policy is to f
15161517

15171518
.. marker-asyncio-end
15181519
1520+
Logging
1521+
^^^^^^^
1522+
.. marker-logging-start
1523+
1524+
The client uses uses Python's `logging <https://docs.python.org/3/library/logging.html>`__ facility for logging the library activity. The following logger categories are exposed:
1525+
1526+
- ``influxdb_client.client.influxdb_client``
1527+
- ``influxdb_client.client.influxdb_client_async``
1528+
- ``influxdb_client.client.write_api``
1529+
- ``influxdb_client.client.write_api_async``
1530+
- ``influxdb_client.client.write.retry``
1531+
- ``influxdb_client.client.write.dataframe_serializer``
1532+
- ``influxdb_client.client.util.multiprocessing_helper``
1533+
- ``influxdb_client.client.exceptions``
1534+
1535+
The default logging level is `warning` without configured logger output. You can use the standard logger interface to change the log level and handler:
1536+
1537+
.. code-block:: python
1538+
1539+
import logging
1540+
import sys
1541+
1542+
from influxdb_client import InfluxDBClient
1543+
1544+
with InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org") as client:
1545+
for _, logger in client.conf.loggers.items():
1546+
logger.setLevel(logging.DEBUG)
1547+
logger.addHandler(logging.StreamHandler(sys.stdout))
1548+
1549+
Debugging
1550+
"""""""""
1551+
1552+
For debug purpose you can enable verbose logging of HTTP requests and set the ``debug`` level to all client's logger categories by:
1553+
1554+
.. code-block:: python
1555+
1556+
client = InfluxDBClient(url="http://localhost:8086", token="my-token", debug=True)
1557+
1558+
.. note::
1559+
1560+
Both HTTP request headers and body will be logged to standard output.
1561+
1562+
.. marker-logging-end
1563+
15191564
Local tests
15201565
-----------
15211566

docs/usage.rst

+5-8
Original file line numberDiff line numberDiff line change
@@ -58,15 +58,12 @@ How to use Asyncio
5858
:start-after: marker-asyncio-start
5959
:end-before: marker-asyncio-end
6060

61-
Debugging
62-
^^^^^^^^^
61+
Logging
62+
^^^^^^^
6363

64-
For debug purpose you can enable verbose logging of http requests.
65-
Both request header and body will be logged to standard output.
66-
67-
.. code-block:: python
68-
69-
_client = InfluxDBClient(url="http://localhost:8086", token="my-token", debug=True, org="my-org")
64+
.. include:: ../README.rst
65+
:start-after: marker-logging-start
66+
:end-before: marker-logging-end
7067

7168
Examples
7269
^^^^^^^^

influxdb_client/_async/rest.py

-6
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010

1111
import io
1212
import json
13-
import logging
1413
import re
1514
import ssl
1615

@@ -22,8 +21,6 @@
2221
from influxdb_client.rest import ApiException
2322
from influxdb_client.rest import _UTF_8_encoding
2423

25-
logger = logging.getLogger(__name__)
26-
2724

2825
async def _on_request_start(session, trace_config_ctx, params):
2926
print(f">>> Request: '{params.method} {params.url}'")
@@ -229,9 +226,6 @@ async def request(self, method, url, query_params=None, headers=None,
229226
data = await r.read()
230227
r = RESTResponseAsync(r, data)
231228

232-
# log response body
233-
logger.debug("response body: %s", r.data)
234-
235229
if not 200 <= r.status <= 299:
236230
raise ApiException(http_resp=r)
237231

influxdb_client/_sync/rest.py

-7
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414

1515
import io
1616
import json
17-
import logging
1817
import re
1918
import ssl
2019

@@ -30,9 +29,6 @@
3029
raise ImportError('OpenAPI Python client requires urllib3.')
3130

3231

33-
logger = logging.getLogger(__name__)
34-
35-
3632
class RESTResponse(io.IOBase):
3733
"""NOTE: This class is auto generated by OpenAPI Generator.
3834
@@ -247,9 +243,6 @@ def request(self, method, url, query_params=None, headers=None,
247243
if six.PY3:
248244
r.data = r.data.decode('utf8')
249245

250-
# log response body
251-
logger.debug("response body: %s", r.data)
252-
253246
if not 200 <= r.status <= 299:
254247
raise ApiException(http_resp=r)
255248

influxdb_client/client/_base.py

+18-2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import codecs
66
import configparser
77
import csv
8+
import logging
89
import os
910
from datetime import datetime, timedelta
1011
from typing import Iterator, List, Generator, Any, Union, Iterable, AsyncGenerator
@@ -29,11 +30,22 @@
2930
except ModuleNotFoundError:
3031
_HAS_DATACLASS = False
3132

33+
LOGGERS_NAMES = [
34+
'influxdb_client.client.influxdb_client',
35+
'influxdb_client.client.influxdb_client_async',
36+
'influxdb_client.client.write_api',
37+
'influxdb_client.client.write_api_async',
38+
'influxdb_client.client.write.retry',
39+
'influxdb_client.client.write.dataframe_serializer',
40+
'influxdb_client.client.util.multiprocessing_helper',
41+
'influxdb_client.client.exceptions'
42+
]
43+
3244

3345
# noinspection PyMethodMayBeStatic
3446
class _BaseClient(object):
3547
def __init__(self, url, token, debug=None, timeout=10_000, enable_gzip=False, org: str = None,
36-
default_tags: dict = None, **kwargs) -> None:
48+
default_tags: dict = None, http_client_logger: str = None, **kwargs) -> None:
3749
self.url = url
3850
self.token = token
3951
self.org = org
@@ -46,13 +58,17 @@ def __init__(self, url, token, debug=None, timeout=10_000, enable_gzip=False, or
4658
else:
4759
self.conf.host = self.url
4860
self.conf.enable_gzip = enable_gzip
49-
self.conf.debug = debug
5061
self.conf.verify_ssl = kwargs.get('verify_ssl', True)
5162
self.conf.ssl_ca_cert = kwargs.get('ssl_ca_cert', None)
5263
self.conf.proxy = kwargs.get('proxy', None)
5364
self.conf.proxy_headers = kwargs.get('proxy_headers', None)
5465
self.conf.connection_pool_maxsize = kwargs.get('connection_pool_maxsize', self.conf.connection_pool_maxsize)
5566
self.conf.timeout = timeout
67+
# logging
68+
self.conf.loggers["http_client_logger"] = logging.getLogger(http_client_logger)
69+
for client_logger in LOGGERS_NAMES:
70+
self.conf.loggers[client_logger] = logging.getLogger(client_logger)
71+
self.conf.debug = debug
5672

5773
auth_token = self.token
5874
self.auth_header_name = "Authorization"

influxdb_client/client/exceptions.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
from urllib3 import HTTPResponse
66

7-
logger = logging.getLogger(__name__)
7+
logger = logging.getLogger('influxdb_client.client.exceptions')
88

99

1010
class InfluxDBError(Exception):

influxdb_client/client/influxdb_client.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def __init__(self, url, token, debug=None, timeout=10_000, enable_gzip=False, or
5353
:key list[str] profilers: list of enabled Flux profilers
5454
"""
5555
super().__init__(url=url, token=token, debug=debug, timeout=timeout, enable_gzip=enable_gzip, org=org,
56-
default_tags=default_tags, **kwargs)
56+
default_tags=default_tags, http_client_logger="urllib3", **kwargs)
5757

5858
from .._sync.api_client import ApiClient
5959
self.api_client = ApiClient(configuration=self.conf, header_name=self.auth_header_name,

influxdb_client/client/influxdb_client_async.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from influxdb_client.client.write_api import PointSettings
1111
from influxdb_client.client.write_api_async import WriteApiAsync
1212

13-
logger = logging.getLogger('influxdb_client.client.influxdb_client')
13+
logger = logging.getLogger('influxdb_client.client.influxdb_client_async')
1414

1515

1616
class InfluxDBClientAsync(_BaseClient):
@@ -46,7 +46,8 @@ def __init__(self, url, token, org: str = None, debug=None, timeout=10_000, enab
4646
``aiohttp-retry``. :class:`~aiohttp.ClientSession` by default.
4747
:key list[str] profilers: list of enabled Flux profilers
4848
"""
49-
super().__init__(url=url, token=token, org=org, debug=debug, timeout=timeout, enable_gzip=enable_gzip, **kwargs)
49+
super().__init__(url=url, token=token, org=org, debug=debug, timeout=timeout, enable_gzip=enable_gzip,
50+
http_client_logger="aiohttp.client", **kwargs)
5051

5152
# compatibility with Python 3.6
5253
if sys.version_info[:2] >= (3, 7):

influxdb_client/client/util/multiprocessing_helper.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from influxdb_client import InfluxDBClient, WriteOptions
1111
from influxdb_client.client.exceptions import InfluxDBError
1212

13-
logger = logging.getLogger(__name__)
13+
logger = logging.getLogger('influxdb_client.client.util.multiprocessing_helper')
1414

1515

1616
def _success_callback(conf: (str, str, str), data: str):

influxdb_client/client/write/dataframe_serializer.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from influxdb_client import WritePrecision
1212
from influxdb_client.client.write.point import _ESCAPE_KEY, _ESCAPE_STRING, _ESCAPE_MEASUREMENT, DEFAULT_WRITE_PRECISION
1313

14-
logger = logging.getLogger(__name__)
14+
logger = logging.getLogger('influxdb_client.client.write.dataframe_serializer')
1515

1616

1717
def _itertuples(data_frame):

influxdb_client/client/write/retry.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
from influxdb_client.client.exceptions import InfluxDBError
1313

14-
logger = logging.getLogger(__name__)
14+
logger = logging.getLogger('influxdb_client.client.write.retry')
1515

1616

1717
class WritesRetry(Retry):

influxdb_client/client/write_api.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
from influxdb_client.client.write.retry import WritesRetry
2424
from influxdb_client.rest import _UTF_8_encoding
2525

26-
logger = logging.getLogger(__name__)
26+
logger = logging.getLogger('influxdb_client.client.write_api')
2727

2828

2929
if _HAS_DATACLASS:

influxdb_client/client/write_api_async.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from influxdb_client.client.write.point import DEFAULT_WRITE_PRECISION
1010
from influxdb_client.client.write_api import PointSettings
1111

12-
logger = logging.getLogger('influxdb_client.client.influxdb_client')
12+
logger = logging.getLogger('influxdb_client.client.write_api_async')
1313

1414
if _HAS_DATACLASS:
1515
from dataclasses import dataclass

influxdb_client/configuration.py

+4-6
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,7 @@ def __init__(self):
7070
self.password = ""
7171

7272
# Logging Settings
73-
self.logger = {}
74-
self.logger["package_logger"] = logging.getLogger("influxdb_client")
75-
self.logger["urllib3_logger"] = logging.getLogger("urllib3")
73+
self.loggers = {}
7674
# Log format
7775
self.logger_format = '%(asctime)s %(levelname)s %(message)s'
7876
# Log stream handler
@@ -145,7 +143,7 @@ def logger_file(self, value):
145143
# then add file handler and remove stream handler.
146144
self.logger_file_handler = logging.FileHandler(self.__logger_file)
147145
self.logger_file_handler.setFormatter(self.logger_formatter)
148-
for _, logger in six.iteritems(self.logger):
146+
for _, logger in six.iteritems(self.loggers):
149147
logger.addHandler(self.logger_file_handler)
150148

151149
@property
@@ -167,14 +165,14 @@ def debug(self, value):
167165
self.__debug = value
168166
if self.__debug:
169167
# if debug status is True, turn on debug logging
170-
for _, logger in six.iteritems(self.logger):
168+
for _, logger in six.iteritems(self.loggers):
171169
logger.setLevel(logging.DEBUG)
172170
# turn on httplib debug
173171
httplib.HTTPConnection.debuglevel = 1
174172
else:
175173
# if debug status is False, turn off debug logging,
176174
# setting log level to default `logging.WARNING`
177-
for _, logger in six.iteritems(self.logger):
175+
for _, logger in six.iteritems(self.loggers):
178176
logger.setLevel(logging.WARNING)
179177
# turn off httplib debug
180178
httplib.HTTPConnection.debuglevel = 0

0 commit comments

Comments
 (0)