Skip to content

Commit 09c9a0f

Browse files
authored
PYCO-76: Logging Improvements (#6)
Changes ------- * Add logger to test environment * Allow initial log message, `Python Couchbase Analytics Client ({PYCBAC_VERSION})`, to display if either root logger has a handler or PYCBAC_LOG_LEVEL environment is set.
1 parent 45a646c commit 09c9a0f

9 files changed

Lines changed: 39 additions & 22 deletions

File tree

couchbase_analytics/protocol/__init__.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,13 @@ def configure_logger() -> None:
3535
import os
3636

3737
log_level = os.getenv('PYCBAC_LOG_LEVEL', None)
38-
if log_level:
38+
handlers_setup = logging.getLogger().hasHandlers()
39+
if log_level is not None or handlers_setup:
3940
logger = logging.getLogger()
40-
if not logger.hasHandlers():
41+
if not handlers_setup:
4142
from couchbase_analytics.common.logging import LOG_DATE_FORMAT, LOG_FORMAT
4243

44+
log_level = log_level or 'INFO'
4345
logging.basicConfig(format=LOG_FORMAT, datefmt=LOG_DATE_FORMAT, level=log_level.upper())
4446
logger.info(f'Python Couchbase Analytics Client ({PYCBAC_VERSION})')
4547

couchbase_analytics/tests/test_server_t.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,6 @@ def test_error_retriable_response_retries_exceeded(self, test_env: BlockingTestE
122122
with pytest.raises(QueryError) as ex:
123123
test_env.cluster_or_scope.execute_query(statement, q_opts)
124124

125-
print(ex.value)
126125
test_env.assert_error_context_num_attempts(allowed_retries + 1, ex.value._context)
127126
test_env.assert_error_context_contains_last_dispatch(ex.value._context)
128127

tests/__init__.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,13 @@
1313
# See the License for the specific language governing permissions and
1414
# limitations under the License.
1515

16+
import logging
1617
from enum import Enum
1718
from typing import AsyncGenerator, Generator, Optional, TypeVar
1819

20+
TEST_LOGGER_NAME = 'couchbase_analytics_test'
21+
logger = logging.getLogger(TEST_LOGGER_NAME)
22+
1923
T = TypeVar('T')
2024
AsyncYieldFixture = AsyncGenerator[T, None]
2125
YieldFixture = Generator[T, None, None]

tests/environments/base_environment.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from __future__ import annotations
1717

1818
import json
19+
import logging
1920
import pathlib
2021
import sys
2122
from os import path
@@ -37,7 +38,7 @@
3738
from couchbase_analytics.options import ClusterOptions, SecurityOptions
3839
from couchbase_analytics.result import BlockingQueryResult
3940
from couchbase_analytics.scope import Scope
40-
from tests import AnalyticsTestEnvironmentError
41+
from tests import TEST_LOGGER_NAME, AnalyticsTestEnvironmentError
4142
from tests.test_server import ResultType
4243
from tests.utils._run_web_server import WebServerHandler
4344

@@ -47,6 +48,8 @@
4748

4849
TEST_AIRLINE_DATA_PATH = path.join(pathlib.Path(__file__).parent.parent, 'test_data', 'airline.json')
4950

51+
logger = logging.getLogger(TEST_LOGGER_NAME)
52+
5053

5154
class TestEnvironmentOptionsKwargs(TypedDict, total=False):
5255
async_cluster: Optional[AsyncCluster]
@@ -199,15 +202,14 @@ def enable_test_server(self) -> BlockingTestEnvironment:
199202
from tests.utils._client_adapter import _TestClientAdapter
200203
from tests.utils._test_httpx import TestHTTPTransport
201204

202-
print(f'{self._cluster=}')
203205
new_adapter = _TestClientAdapter(
204206
adapter=self._cluster._impl._client_adapter,
205207
http_transport_cls=TestHTTPTransport,
206208
)
207209
new_adapter.create_client()
208210
self._cluster._impl._client_adapter = new_adapter
209211
url = self._cluster._impl.client_adapter.connection_details.url.get_formatted_url()
210-
print(f'Connecting to test server at {url}')
212+
logger.info(f'Connecting to test server at {url}')
211213
self._server_handler.start_server()
212214
self.warmup_test_server()
213215
return self
@@ -336,6 +338,7 @@ def get_environment(
336338
else:
337339
sec_opts = SecurityOptions(disable_server_certificate_verification=True)
338340

341+
logger.info(f'Creating Cluster with options={env_opts}')
339342
if sec_opts is not None:
340343
opts = ClusterOptions(security_options=sec_opts)
341344
env_opts['cluster'] = Cluster.create_instance(connstr, cred, opts)
@@ -425,7 +428,7 @@ async def enable_test_server(self) -> AsyncTestEnvironment:
425428
await new_adapter.create_client()
426429
self._async_cluster._impl._client_adapter = new_adapter
427430
url = self._async_cluster._impl.client_adapter.connection_details.url.get_formatted_url()
428-
print(f'Connecting to test server at {url}')
431+
logger.info(f'Connecting to test server at {url}')
429432
self._server_handler.start_server()
430433
await self.warmup_test_server()
431434
return self
@@ -559,7 +562,7 @@ def get_environment(
559562
else:
560563
sec_opts = SecurityOptions(disable_server_certificate_verification=True)
561564

562-
print(f'{env_opts=}')
565+
logger.info(f'Creating AsyncCluster with options={env_opts}')
563566
if sec_opts is not None:
564567
opts = ClusterOptions(security_options=sec_opts)
565568
env_opts['async_cluster'] = AsyncCluster.create_instance(connstr, cred, opts)
@@ -574,27 +577,27 @@ def get_environment(
574577

575578
@pytest.fixture(scope='class', name='sync_test_env')
576579
def base_test_environment(analytics_config: AnalyticsConfig) -> BlockingTestEnvironment:
577-
print('Creating sync test environment')
580+
logger.info('Creating sync test environment')
578581
return BlockingTestEnvironment.get_environment(analytics_config)
579582

580583

581584
@pytest.fixture(scope='class', name='sync_test_env_with_server')
582585
def base_test_environment_with_server(analytics_config: AnalyticsConfig) -> BlockingTestEnvironment:
583-
print('Creating sync test environment w/ test server')
586+
logger.info('Creating sync test environment w/ test server')
584587
server_handler = WebServerHandler()
585588
return BlockingTestEnvironment.get_environment(analytics_config, server_handler=server_handler)
586589

587590

588591
@pytest.fixture(scope='class', name='async_test_env')
589592
def base_async_test_environment(analytics_config: AnalyticsConfig, anyio_backend: str) -> AsyncTestEnvironment:
590-
print('Creating async test environment')
593+
logger.info('Creating async test environment')
591594
return AsyncTestEnvironment.get_environment(analytics_config, backend=anyio_backend)
592595

593596

594597
@pytest.fixture(scope='class', name='async_test_env_with_server')
595598
def base_async_test_environment_with_server(
596599
analytics_config: AnalyticsConfig, anyio_backend: str
597600
) -> AsyncTestEnvironment:
598-
print('Creating async test environment w/ test server')
601+
logger.info('Creating async test environment w/ test server')
599602
server_handler = WebServerHandler()
600603
return AsyncTestEnvironment.get_environment(analytics_config, server_handler=server_handler, backend=anyio_backend)

tests/test_config.ini

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[analytics]
22
scheme = http
3-
host = 3585106b-20250708.cb-sdk.bemdas.com
3+
host = 192.168.107.129
44
port = 8095
55
username = Administrator
66
password = password

tests/utils/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,6 @@ async def __anext__(self) -> bytes:
8181
if len(self._data) == 0:
8282
raise StopAsyncIteration
8383
if len(self._end_data) > 0:
84-
print(f'end_data={self._end_data}')
8584
# ending a results array
8685
self._data += b'], '
8786
self._data += bytearray(self._end_data)

tests/utils/_run_web_server.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,6 @@
2424

2525
WEB_SERVER_PATH = path.join(pathlib.Path(__file__).parent.parent, 'test_server', 'web_server.py')
2626

27-
print(f'Web server script path: {WEB_SERVER_PATH}')
28-
2927
logging.basicConfig(
3028
level=logging.INFO, stream=sys.stderr, format='%(asctime)s - %(levelname)s - (PID:%(process)d) - %(message)s'
3129
)

tests/utils/_test_async_httpx.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import logging
12
import typing
23

34
from httpcore import AsyncConnectionPool, Origin, Request, Response
@@ -10,6 +11,10 @@
1011
from httpcore._trace import Trace
1112
from httpx import AsyncHTTPTransport, Limits, create_ssl_context
1213

14+
from tests import TEST_LOGGER_NAME
15+
16+
cb_logger = logging.getLogger(TEST_LOGGER_NAME)
17+
1318

1419
class TestAsyncHTTPConnection(AsyncHTTPConnection):
1520
def __init__(self, *args, **kwargs) -> None: # type: ignore
@@ -19,9 +24,10 @@ async def _connect(self, request: Request) -> AsyncNetworkStream:
1924
timeouts = request.extensions.get('timeout', {})
2025
sni_hostname = request.extensions.get('sni_hostname', None)
2126
timeout = timeouts.get('connect', None)
22-
# TESTING_OVERRIDE
27+
# -- START PYCBAC TESTING --
2328
test_connect_timeout = timeouts.get('test_connect_timeout', None)
24-
print(f'PYCBAC OVERRIDE: connect timeout: {timeout}, test_connect_timeout: {test_connect_timeout}')
29+
cb_logger.debug(f'PYCBAC OVERRIDE: connect timeout: {timeout}, test_connect_timeout: {test_connect_timeout}')
30+
# -- END PYCBAC TESTING --
2531

2632
retries_left = self._retries
2733
delays = exponential_backoff(factor=RETRIES_BACKOFF_FACTOR)
@@ -144,9 +150,10 @@ async def handle_async_request(self, request: Request) -> Response:
144150

145151
timeouts = request.extensions.get('timeout', {})
146152
timeout = timeouts.get('pool', None)
147-
# TESTING_OVERRIDE
153+
# -- START PYCBAC TESTING --
148154
test_pool_timeout = timeouts.get('test_pool_timeout', None)
149-
print(f'PYCBAC OVERRIDE: pool timeout: {timeout}, test_pool_timeout: {test_pool_timeout}')
155+
cb_logger.debug(f'PYCBAC OVERRIDE: pool timeout: {timeout}, test_pool_timeout: {test_pool_timeout}')
156+
# -- END PYCBAC TESTING --
150157

151158
with self._optional_thread_lock:
152159
# Add the incoming request to our request queue.

tests/utils/_test_httpx.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import logging
12
import time
23
import typing
34

@@ -11,6 +12,10 @@
1112
from httpcore._trace import Trace
1213
from httpx import HTTPTransport, Limits, create_ssl_context
1314

15+
from tests import TEST_LOGGER_NAME
16+
17+
cb_logger = logging.getLogger(TEST_LOGGER_NAME)
18+
1419

1520
class TestHTTPConnection(HTTPConnection):
1621
def __init__(self, *args, **kwargs) -> None: # type: ignore
@@ -22,7 +27,7 @@ def _connect(self, request: Request) -> NetworkStream:
2227
timeout = timeouts.get('connect', None)
2328
# -- START PYCBAC TESTING --
2429
test_connect_timeout = timeouts.get('test_connect_timeout', None)
25-
print(f'PYCBAC OVERRIDE: connect timeout: {timeout}, test_connect_timeout: {test_connect_timeout}')
30+
cb_logger.debug(f'PYCBAC OVERRIDE: connect timeout: {timeout}, test_connect_timeout: {test_connect_timeout}')
2631
# -- END PYCBAC TESTING --
2732

2833
retries_left = self._retries
@@ -158,7 +163,7 @@ def handle_request(self, request: Request) -> Response:
158163
timeout = timeouts.get('pool', None)
159164
# -- START PYCBAC TESTING --
160165
test_pool_timeout = timeouts.get('test_pool_timeout', None)
161-
print(f'PYCBAC OVERRIDE: pool timeout: {timeout}, test_pool_timeout: {test_pool_timeout}')
166+
cb_logger.debug(f'PYCBAC OVERRIDE: pool timeout: {timeout}, test_pool_timeout: {test_pool_timeout}')
162167
# -- END PYCBAC TESTING --
163168

164169
with self._optional_thread_lock:

0 commit comments

Comments
 (0)