Skip to content

Commit 2f3edcc

Browse files
BobTheBuidlerfselmo
authored andcommitted
feat: build log messages lazily
- Create 3643.performance.rst - chore: black . - fix: linter errors
1 parent 7c084e0 commit 2f3edcc

File tree

14 files changed

+151
-99
lines changed

14 files changed

+151
-99
lines changed

docs/filters.rst

Lines changed: 7 additions & 4 deletions
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

newsfragments/3643.performance.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
optimize message formatting for logging

web3/_utils/caching/request_caching_validation.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,8 @@ 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",
77+
threshold,
7778
)
7879
return False
7980
except Exception as e:
@@ -128,7 +129,8 @@ def validate_from_blocknum_in_result(
128129
else:
129130
provider.logger.error(
130131
"Could not find block number in result. This should not have happened. "
131-
f"Request not cached.\n result: {result}",
132+
"Request not cached.\n result: %s",
133+
result,
132134
)
133135
return False
134136
except Exception as e:
@@ -198,7 +200,8 @@ async def async_is_beyond_validation_threshold(
198200
else:
199201
provider.logger.error(
200202
"Invalid request_cache_validation_threshold value. This should not "
201-
f"have happened. Request not cached.\n threshold: {threshold}"
203+
"have happened. Request not cached.\n threshold: %s",
204+
threshold,
202205
)
203206
return False
204207
except Exception as e:
@@ -253,7 +256,8 @@ async def async_validate_from_blocknum_in_result(
253256
else:
254257
provider.logger.error(
255258
"Could not find block number in result. This should not have happened. "
256-
f"Request not cached.\n result: {result}",
259+
"Request not cached.\n result: %s",
260+
result,
257261
)
258262
return False
259263
except Exception as e:

web3/_utils/http_session_manager.py

Lines changed: 17 additions & 14 deletions
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,19 @@ 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",
230+
cached_session,
228231
)
229232

230233
# replace stale session with a new session at the cache key
@@ -238,7 +241,7 @@ async def async_cache_and_return_session(
238241
cache_key, _session
239242
)
240243
self.logger.debug(
241-
f"Async session cached: {endpoint_uri}, {cached_session}"
244+
"Async session cached: %s, %s", endpoint_uri, cached_session
242245
)
243246

244247
if evicted_items is not None:
@@ -248,8 +251,8 @@ async def async_cache_and_return_session(
248251
evicted_sessions = list(evicted_items.values())
249252
for evicted_session in evicted_sessions:
250253
self.logger.debug(
251-
"Async session cache full. Session evicted from cache: "
252-
f"{evicted_session}",
254+
"Async session cache full. Session evicted from cache: %s",
255+
evicted_session,
253256
)
254257
# Kick off an asyncio `Task` to close the evicted sessions. In the case
255258
# that the cache filled very quickly and some sessions have been evicted
@@ -323,10 +326,10 @@ async def _async_close_evicted_sessions(
323326

324327
for evicted_session in evicted_sessions:
325328
await evicted_session.close()
326-
self.logger.debug(f"Closed evicted async session: {evicted_session}")
329+
self.logger.debug("Closed evicted async session: %s", evicted_session)
327330

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

web3/_utils/validation.py

Lines changed: 1 addition & 1 deletion
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

web3/manager.py

Lines changed: 23 additions & 14 deletions
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,8 @@ 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",
414+
rpc_request,
408415
)
409416
response = await recv_func(rpc_request)
410417
try:
@@ -417,8 +424,8 @@ async def recv_for_request(self, rpc_request: RPCRequest) -> RPCResponse:
417424
async def recv(self) -> Union[RPCResponse, FormattedEthSubscriptionResponse]:
418425
provider = cast(PersistentConnectionProvider, self._provider)
419426
self.logger.debug(
420-
"Getting next response from open socket connection: "
421-
f"{provider.get_endpoint_uri_or_ipc_path()}"
427+
"Getting next response from open socket connection: %s",
428+
provider.get_endpoint_uri_or_ipc_path(),
422429
)
423430
# pop from the queue since the listener task is responsible for reading
424431
# directly from the socket
@@ -501,9 +508,11 @@ async def _process_response(
501508
# subscription as it comes in
502509
request_info.subscription_id = subscription_id
503510
provider.logger.debug(
504-
"Caching eth_subscription info:\n "
505-
f"cache_key={cache_key},\n "
506-
f"request_info={request_info.__dict__}"
511+
"Caching eth_subscription info:\n"
512+
" cache_key=%s,\n"
513+
" request_info=%s",
514+
cache_key,
515+
request_info.__dict__,
507516
)
508517
self._request_processor._request_information_cache.cache(
509518
cache_key, request_info

web3/providers/ipc.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ def _make_request(self, request: bytes) -> RPCResponse:
197197
@handle_request_caching
198198
def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
199199
self.logger.debug(
200-
f"Making request IPC. Path: {self.ipc_path}, Method: {method}"
200+
"Making request IPC. Path: %s, Method: %s", self.ipc_path, method
201201
)
202202
request = self.encode_rpc_request(method, params)
203203
return self._make_request(request)
@@ -206,7 +206,7 @@ def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
206206
def make_batch_request(
207207
self, requests: List[Tuple[RPCEndpoint, Any]]
208208
) -> List[RPCResponse]:
209-
self.logger.debug(f"Making batch request IPC. Path: {self.ipc_path}")
209+
self.logger.debug("Making batch request IPC. Path: %s", self.ipc_path)
210210
request_data = self.encode_batch_rpc_request(requests)
211211
response = cast(List[RPCResponse], self._make_request(request_data))
212212
return sort_batch_response_by_response_ids(response)

web3/providers/legacy_websocket.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ async def coro_make_request(self, request_data: bytes) -> RPCResponse:
136136
@handle_request_caching
137137
def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
138138
self.logger.debug(
139-
f"Making request WebSocket. URI: {self.endpoint_uri}, " f"Method: {method}"
139+
"Making request WebSocket. URI: %s, Method: %s", self.endpoint_uri, method
140140
)
141141
request_data = self.encode_rpc_request(method, params)
142142
future = asyncio.run_coroutine_threadsafe(
@@ -149,8 +149,9 @@ 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,
154+
requests,
154155
)
155156
request_data = self.encode_batch_rpc_request(requests)
156157
future = asyncio.run_coroutine_threadsafe(

0 commit comments

Comments
 (0)