Skip to content

Commit 2944ba4

Browse files
committed
feat: build log messages lazily
1 parent 7946dcf commit 2944ba4

13 files changed

+121
-101
lines changed

Diff for: docs/filters.rst

+7-4
Original file line numberDiff line numberDiff line change
@@ -654,7 +654,7 @@ The script can be run with: ``python ./eventscanner.py <your JSON-RPC API URL>``
654654
# from our in-memory cache
655655
block_when = get_block_when(block_number)
656656
657-
logger.debug(f"Processing event {evt['event']}, block: {evt['blockNumber']} count: {evt['blockNumber']}")
657+
logger.debug("Processing event %s, block: %s count: %s", evt['event'], block_number, block_number)
658658
processed = self.state.process_event(block_when, evt)
659659
all_processed.append(processed)
660660
@@ -726,7 +726,8 @@ The script can be run with: ``python ./eventscanner.py <your JSON-RPC API URL>``
726726
# Print some diagnostics to logs to try to fiddle with real world JSON-RPC API performance
727727
estimated_end_block = min(current_block + chunk_size, end_block)
728728
logger.debug(
729-
f"Scanning token transfers for blocks: {current_block} - {estimated_end_block}, chunk size {chunk_size}, last chunk scan took {last_scan_duration}, last logs found {last_logs_found}"
729+
"Scanning token transfers for blocks: %s - %s, chunk size %s, last chunk scan took %s, last logs found %s",
730+
current_block, estimated_end_block, chunk_size, last_scan_duration, last_logs_found,
730731
)
731732
732733
start = time.time()
@@ -778,7 +779,9 @@ The script can be run with: ``python ./eventscanner.py <your JSON-RPC API URL>``
778779
if i < retries - 1:
779780
# Give some more verbose info than the default middleware
780781
logger.warning(
781-
f"Retrying events for block range {start_block} - {end_block} ({end_block-start_block}) failed with {e} , retrying in {delay} seconds")
782+
"Retrying events for block range %s - %s (%s) failed with %s , retrying in %s seconds",
783+
start_block, end_block, end_block-start_block, e, delay,
784+
)
782785
# Decrease the `eth_getBlocks` range
783786
end_block = start_block + ((end_block - start_block) // 2)
784787
# Let the JSON-RPC to recover e.g. from restart
@@ -832,7 +835,7 @@ The script can be run with: ``python ./eventscanner.py <your JSON-RPC API URL>``
832835
to_block=to_block
833836
)
834837
835-
logger.debug(f"Querying eth_getLogs with the following parameters: {event_filter_params}")
838+
logger.debug("Querying eth_getLogs with the following parameters: %s", event_filter_params)
836839
837840
# Call JSON-RPC API on your Ethereum node.
838841
# get_logs() returns raw AttributedDict entries

Diff for: web3/_utils/caching/request_caching_validation.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ def is_beyond_validation_threshold(
7373
else:
7474
provider.logger.error(
7575
"Invalid request_cache_validation_threshold value. This should not "
76-
f"have happened. Request not cached.\n threshold: {threshold}"
76+
"have happened. Request not cached.\n threshold: %s", threshold
7777
)
7878
return False
7979
except Exception as e:
@@ -128,7 +128,7 @@ def validate_from_blocknum_in_result(
128128
else:
129129
provider.logger.error(
130130
"Could not find block number in result. This should not have happened. "
131-
f"Request not cached.\n result: {result}",
131+
"Request not cached.\n result: %s", result
132132
)
133133
return False
134134
except Exception as e:
@@ -198,7 +198,7 @@ async def async_is_beyond_validation_threshold(
198198
else:
199199
provider.logger.error(
200200
"Invalid request_cache_validation_threshold value. This should not "
201-
f"have happened. Request not cached.\n threshold: {threshold}"
201+
"have happened. Request not cached.\n threshold: %s", threshold
202202
)
203203
return False
204204
except Exception as e:
@@ -253,7 +253,7 @@ async def async_validate_from_blocknum_in_result(
253253
else:
254254
provider.logger.error(
255255
"Could not find block number in result. This should not have happened. "
256-
f"Request not cached.\n result: {result}",
256+
"Request not cached.\n result: %s", result
257257
)
258258
return False
259259
except Exception as e:

Diff for: web3/_utils/http_session_manager.py

+16-14
Original file line numberDiff line numberDiff line change
@@ -81,14 +81,14 @@ def cache_and_return_session(
8181

8282
with self._lock:
8383
cached_session, evicted_items = self.session_cache.cache(cache_key, session)
84-
self.logger.debug(f"Session cached: {endpoint_uri}, {cached_session}")
84+
self.logger.debug("Session cached: %s, %s", endpoint_uri, cached_session)
8585

8686
if evicted_items is not None:
8787
evicted_sessions = evicted_items.values()
8888
for evicted_session in evicted_sessions:
8989
self.logger.debug(
90-
"Session cache full. Session evicted from cache: "
91-
f"{evicted_session}",
90+
"Session cache full. Session evicted from cache: %s",
91+
evicted_session,
9292
)
9393
threading.Timer(
9494
# If `request_timeout` is `None`, don't wait forever for the closing
@@ -167,7 +167,7 @@ def _handle_streaming_response(
167167
def _close_evicted_sessions(self, evicted_sessions: List[requests.Session]) -> None:
168168
for evicted_session in evicted_sessions:
169169
evicted_session.close()
170-
self.logger.debug(f"Closed evicted session: {evicted_session}")
170+
self.logger.debug("Closed evicted session: %s", evicted_session)
171171

172172
# -- async -- #
173173

@@ -195,7 +195,7 @@ async def async_cache_and_return_session(
195195
cache_key, session
196196
)
197197
self.logger.debug(
198-
f"Async session cached: {endpoint_uri}, {cached_session}"
198+
"Async session cached: %s, %s", endpoint_uri, cached_session
199199
)
200200

201201
else:
@@ -215,16 +215,18 @@ async def async_cache_and_return_session(
215215
)
216216
if warning:
217217
self.logger.debug(
218-
f"{warning}: {endpoint_uri}, {cached_session}. "
219-
f"Creating and caching a new async session for uri."
218+
"%s: %s, %s. Creating and caching a new async session for uri.",
219+
warning,
220+
endpoint_uri,
221+
cached_session,
220222
)
221223

222224
self.session_cache._data.pop(cache_key)
223225
if not session_is_closed:
224226
# if loop was closed but not the session, close the session
225227
await cached_session.close()
226228
self.logger.debug(
227-
f"Async session closed and evicted from cache: {cached_session}"
229+
"Async session closed and evicted from cache: %s", cached_session
228230
)
229231

230232
# replace stale session with a new session at the cache key
@@ -238,7 +240,7 @@ async def async_cache_and_return_session(
238240
cache_key, _session
239241
)
240242
self.logger.debug(
241-
f"Async session cached: {endpoint_uri}, {cached_session}"
243+
"Async session cached: %s, %s", endpoint_uri, cached_session
242244
)
243245

244246
if evicted_items is not None:
@@ -248,8 +250,8 @@ async def async_cache_and_return_session(
248250
evicted_sessions = list(evicted_items.values())
249251
for evicted_session in evicted_sessions:
250252
self.logger.debug(
251-
"Async session cache full. Session evicted from cache: "
252-
f"{evicted_session}",
253+
"Async session cache full. Session evicted from cache: %s",
254+
evicted_session,
253255
)
254256
# Kick off an asyncio `Task` to close the evicted sessions. In the case
255257
# that the cache filled very quickly and some sessions have been evicted
@@ -323,10 +325,10 @@ async def _async_close_evicted_sessions(
323325

324326
for evicted_session in evicted_sessions:
325327
await evicted_session.close()
326-
self.logger.debug(f"Closed evicted async session: {evicted_session}")
328+
self.logger.debug("Closed evicted async session: %s", evicted_session)
327329

328330
if any(not evicted_session.closed for evicted_session in evicted_sessions):
329331
self.logger.warning(
330-
"Some evicted async sessions were not properly closed: "
331-
f"{evicted_sessions}"
332+
"Some evicted async sessions were not properly closed: %s",
333+
evicted_sessions
332334
)

Diff for: web3/_utils/validation.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -396,7 +396,7 @@ def validate_rpc_response_and_raise_if_error(
396396

397397
response = apply_error_formatters(error_formatters, response)
398398
if logger is not None:
399-
logger.debug(f"RPC error response: {response}")
399+
logger.debug("RPC error response: %s", response)
400400

401401
raise web3_rpc_error
402402

Diff for: web3/manager.py

+22-14
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ def _make_request(
159159
request_func = provider.request_func(
160160
cast("Web3", self.w3), cast("MiddlewareOnion", self.middleware_onion)
161161
)
162-
self.logger.debug(f"Making request. Method: {method}")
162+
self.logger.debug("Making request. Method: %s", method)
163163
return request_func(method, params)
164164

165165
async def _coro_make_request(
@@ -169,7 +169,7 @@ async def _coro_make_request(
169169
request_func = await provider.request_func(
170170
cast("AsyncWeb3", self.w3), cast("MiddlewareOnion", self.middleware_onion)
171171
)
172-
self.logger.debug(f"Making request. Method: {method}")
172+
self.logger.debug("Making request. Method: %s", method)
173173
return await request_func(method, params)
174174

175175
#
@@ -366,9 +366,12 @@ async def socket_request(
366366
) -> RPCResponse:
367367
provider = cast(PersistentConnectionProvider, self._provider)
368368
self.logger.debug(
369-
"Making request to open socket connection and waiting for response: "
370-
f"{provider.get_endpoint_uri_or_ipc_path()},\n method: {method},\n"
371-
f" params: {params}"
369+
"Making request to open socket connection and waiting for response: %s,\n"
370+
" method: %s,\n"
371+
" params: %s",
372+
provider.get_endpoint_uri_or_ipc_path(),
373+
method,
374+
params,
372375
)
373376
rpc_request = await self.send(method, params)
374377
provider._request_processor.cache_request_information(
@@ -388,9 +391,12 @@ async def send(self, method: RPCEndpoint, params: Any) -> RPCRequest:
388391
middleware_onion,
389392
)
390393
self.logger.debug(
391-
"Sending request to open socket connection: "
392-
f"{provider.get_endpoint_uri_or_ipc_path()},\n method: {method},\n"
393-
f" params: {params}"
394+
"Sending request to open socket connection: %s,\n"
395+
" method: %s,\n"
396+
" params: %s",
397+
provider.get_endpoint_uri_or_ipc_path(),
398+
method,
399+
params,
394400
)
395401
return await send_func(method, params)
396402

@@ -404,7 +410,7 @@ async def recv_for_request(self, rpc_request: RPCRequest) -> RPCResponse:
404410
)
405411
self.logger.debug(
406412
"Getting response for request from open socket connection:\n"
407-
f" request: {rpc_request}"
413+
" request: %s", rpc_request,
408414
)
409415
response = await recv_func(rpc_request)
410416
try:
@@ -417,8 +423,8 @@ async def recv_for_request(self, rpc_request: RPCRequest) -> RPCResponse:
417423
async def recv(self) -> Union[RPCResponse, FormattedEthSubscriptionResponse]:
418424
provider = cast(PersistentConnectionProvider, self._provider)
419425
self.logger.debug(
420-
"Getting next response from open socket connection: "
421-
f"{provider.get_endpoint_uri_or_ipc_path()}"
426+
"Getting next response from open socket connection: %s",
427+
provider.get_endpoint_uri_or_ipc_path()
422428
)
423429
# pop from the queue since the listener task is responsible for reading
424430
# directly from the socket
@@ -501,9 +507,11 @@ async def _process_response(
501507
# subscription as it comes in
502508
request_info.subscription_id = subscription_id
503509
provider.logger.debug(
504-
"Caching eth_subscription info:\n "
505-
f"cache_key={cache_key},\n "
506-
f"request_info={request_info.__dict__}"
510+
"Caching eth_subscription info:\n"
511+
" cache_key=%s,\n"
512+
" request_info=%s",
513+
cache_key,
514+
request_info.__dict__,
507515
)
508516
self._request_processor._request_information_cache.cache(
509517
cache_key, request_info

Diff for: web3/providers/ipc.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -196,15 +196,15 @@ def _make_request(self, request: bytes) -> RPCResponse:
196196
@handle_request_caching
197197
def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
198198
self.logger.debug(
199-
f"Making request IPC. Path: {self.ipc_path}, Method: {method}"
199+
"Making request IPC. Path: %s, Method: %s", self.ipc_path, method
200200
)
201201
request = self.encode_rpc_request(method, params)
202202
return self._make_request(request)
203203

204204
def make_batch_request(
205205
self, requests: List[Tuple[RPCEndpoint, Any]]
206206
) -> List[RPCResponse]:
207-
self.logger.debug(f"Making batch request IPC. Path: {self.ipc_path}")
207+
self.logger.debug("Making batch request IPC. Path: %s", self.ipc_path)
208208
request_data = self.encode_batch_rpc_request(requests)
209209
response = cast(List[RPCResponse], self._make_request(request_data))
210210
return sort_batch_response_by_response_ids(response)

Diff for: web3/providers/legacy_websocket.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ async def coro_make_request(self, request_data: bytes) -> RPCResponse:
137137
@handle_request_caching
138138
def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
139139
self.logger.debug(
140-
f"Making request WebSocket. URI: {self.endpoint_uri}, " f"Method: {method}"
140+
"Making request WebSocket. URI: %s, Method: %s", self.endpoint_uri, method
141141
)
142142
request_data = self.encode_rpc_request(method, params)
143143
future = asyncio.run_coroutine_threadsafe(
@@ -149,8 +149,8 @@ def make_batch_request(
149149
self, requests: List[Tuple[RPCEndpoint, Any]]
150150
) -> List[RPCResponse]:
151151
self.logger.debug(
152-
f"Making batch request WebSocket. URI: {self.endpoint_uri}, "
153-
f"Methods: {requests}"
152+
"Making batch request WebSocket. URI: %s, Methods: %s",
153+
self.endpoint_uri, requests,
154154
)
155155
request_data = self.encode_batch_rpc_request(requests)
156156
future = asyncio.run_coroutine_threadsafe(

Diff for: web3/providers/persistent/persistent.py

+13-20
Original file line numberDiff line numberDiff line change
@@ -171,19 +171,15 @@ async def connect(self) -> None:
171171
while _connection_attempts != self._max_connection_retries:
172172
try:
173173
_connection_attempts += 1
174-
self.logger.info(
175-
f"Connecting to: {self.get_endpoint_uri_or_ipc_path()}"
176-
)
174+
self.logger.info("Connecting to: %s", self.get_endpoint_uri_or_ipc_path())
177175
await self._provider_specific_connect()
178176
self._message_listener_task = asyncio.create_task(
179177
self._message_listener()
180178
)
181179
self._message_listener_task.add_done_callback(
182180
self._message_listener_callback
183181
)
184-
self.logger.info(
185-
f"Successfully connected to: {self.get_endpoint_uri_or_ipc_path()}"
186-
)
182+
self.logger.info("Successfully connected to: %s", self.get_endpoint_uri_or_ipc_path())
187183
break
188184
except (WebSocketException, OSError) as e:
189185
if _connection_attempts == self._max_connection_retries:
@@ -192,8 +188,9 @@ async def connect(self) -> None:
192188
f"Retries exceeded max of {self._max_connection_retries}."
193189
) from e
194190
self.logger.info(
195-
f"Could not connect to: {self.get_endpoint_uri_or_ipc_path()}. "
196-
f"Retrying in {round(_backoff_time, 1)} seconds.",
191+
"Could not connect to: %s. Retrying in %s seconds.",
192+
self.get_endpoint_uri_or_ipc_path(),
193+
round(_backoff_time, 1),
197194
exc_info=True,
198195
)
199196
await asyncio.sleep(_backoff_time)
@@ -213,9 +210,7 @@ async def disconnect(self) -> None:
213210

214211
await self._provider_specific_disconnect()
215212
self._request_processor.clear_caches()
216-
self.logger.info(
217-
f"Successfully disconnected from: {self.get_endpoint_uri_or_ipc_path()}"
218-
)
213+
self.logger.info("Successfully disconnected from: %s", self.get_endpoint_uri_or_ipc_path())
219214

220215
@async_handle_send_caching
221216
async def send_request(self, method: RPCEndpoint, params: Any) -> RPCRequest:
@@ -332,9 +327,9 @@ def _raise_stray_errors_from_cache(self) -> None:
332327

333328
async def _message_listener(self) -> None:
334329
self.logger.info(
335-
f"{self.__class__.__qualname__} listener background task started. Storing "
330+
"%s listener background task started. Storing "
336331
"all messages in appropriate request processor queues / caches to be "
337-
"processed."
332+
"processed.", self.__class__.__qualname__
338333
)
339334
while True:
340335
# the use of sleep(0) seems to be the most efficient way to yield control
@@ -358,8 +353,8 @@ async def _message_listener(self) -> None:
358353
self._raise_stray_errors_from_cache()
359354
except PersistentConnectionClosedOK as e:
360355
self.logger.info(
361-
"Message listener background task has ended gracefully: "
362-
f"{e.user_message}"
356+
"Message listener background task has ended gracefully: %s",
357+
e.user_message,
363358
)
364359
# trigger a return to end the listener task and initiate the callback fn
365360
return
@@ -377,8 +372,8 @@ def _error_log_listener_task_exception(self, e: Exception) -> None:
377372
"""
378373
self.logger.error(
379374
"Exception caught in listener, error logging and keeping "
380-
"listener background task alive."
381-
f"\n error={e.__class__.__name__}: {e}"
375+
"listener background task alive.\n error=%s: %s",
376+
e.__class__.__name__, e
382377
)
383378

384379
def _handle_listener_task_exceptions(self) -> None:
@@ -410,9 +405,7 @@ async def _match_response_id_to_request_id() -> RPCResponse:
410405
self._handle_listener_task_exceptions()
411406

412407
if request_cache_key in self._request_processor._request_response_cache:
413-
self.logger.debug(
414-
f"Popping response for id {request_id} from cache."
415-
)
408+
self.logger.debug("Popping response for id %s from cache.", request_id)
416409
popped_response = await self._request_processor.pop_raw_response(
417410
cache_key=request_cache_key,
418411
)

0 commit comments

Comments
 (0)