Skip to content

Commit e30af8a

Browse files
committed
remove all f-strings from logs
1 parent 9ac1fec commit e30af8a

49 files changed

Lines changed: 290 additions & 265 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

bot/bot.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ async def ping_services(self) -> None:
4040
attempts = 0
4141
while True:
4242
try:
43-
log.info(f"Attempting site connection: {attempts + 1}/{constants.URLs.connect_max_retries}")
43+
log.info("Attempting site connection: %s/%s", attempts + 1, constants.URLs.connect_max_retries)
4444
await self.api_client.get("healthcheck")
4545
break
4646

@@ -55,7 +55,7 @@ async def setup_hook(self) -> None:
5555
await super().setup_hook()
5656
await self.load_extensions(exts)
5757

58-
async def on_error(self, event: str, *args, **kwargs) -> None:
58+
async def on_error(self, event: str, /, *args, **kwargs) -> None:
5959
"""Log errors raised in event listeners rather than printing them to stderr."""
6060
e_val = exception()
6161

@@ -76,4 +76,4 @@ async def on_error(self, event: str, *args, **kwargs) -> None:
7676
scope.set_extra("args", args)
7777
scope.set_extra("kwargs", kwargs)
7878

79-
log.exception(f"Unhandled exception in {event}.")
79+
log.exception("Unhandled exception in %s.", event)

bot/decorators.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -238,9 +238,9 @@ async def wrapper(*args, **kwargs) -> t.Any:
238238

239239
if target.top_role >= actor.top_role:
240240
log.info(
241-
f"{actor} ({actor.id}) attempted to {cmd} "
242-
f"{target} ({target.id}), who has an equal or higher top role."
243-
)
241+
"%s (%s) attempted to %s "
242+
"%s (%s), who has an equal or higher top role.",
243+
actor, actor.id, cmd, target, target.id)
244244
await ctx.send(
245245
f":x: {actor.mention}, you may not {cmd} "
246246
"someone with an equal or higher top role."
@@ -266,7 +266,7 @@ def decorator(func: t.Callable) -> t.Callable:
266266
async def wrapped(*args, **kwargs) -> t.Any:
267267
"""Short-circuit and log if in debug mode."""
268268
if DEBUG_MODE:
269-
log.debug(f"Function {func.__name__} called with args: {args}, kwargs: {kwargs}")
269+
log.debug("Function %s called with args: %s, kwargs: %s", func.__name__, args, kwargs)
270270
return return_value
271271
return await func(*args, **kwargs)
272272
return wrapped

bot/exts/backend/branding/_cog.py

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -144,12 +144,12 @@ async def apply_asset(self, asset_type: AssetType, download_url: str) -> bool:
144144
145145
Return a boolean indicating whether the application was successful.
146146
"""
147-
log.info(f"Applying '{asset_type.value}' asset to the guild.")
147+
log.info("Applying '%s' asset to the guild.", asset_type.value)
148148

149149
try:
150150
file = await self.repository.fetch_file(download_url)
151151
except Exception:
152-
log.exception(f"Failed to fetch '{asset_type.value}' asset.")
152+
log.exception("Failed to fetch '%s' asset.", asset_type.value)
153153
return False
154154

155155
await self.bot.wait_until_guild_available()
@@ -163,7 +163,7 @@ async def apply_asset(self, asset_type: AssetType, download_url: str) -> bool:
163163
log.exception("Asset upload to Discord failed.")
164164
return False
165165
except TimeoutError:
166-
log.error(f"Asset upload to Discord timed out after {timeout} seconds.")
166+
log.error("Asset upload to Discord timed out after %s seconds.", timeout)
167167
return False
168168
else:
169169
log.trace("Asset uploaded successfully.")
@@ -182,17 +182,17 @@ async def rotate_assets(self, asset_type: AssetType) -> bool:
182182
183183
Return a boolean indicating whether a new asset was applied successfully.
184184
"""
185-
log.debug(f"Rotating {asset_type.value}s.")
185+
log.debug("Rotating %ss.", asset_type.value)
186186

187187
state = await self.asset_caches[asset_type].to_dict()
188188
log.trace(f"Total {asset_type.value}s in rotation: {len(state)}.")
189189

190190
if not state: # This would only happen if rotation not initiated, but we can handle gracefully.
191-
log.warning(f"Attempted {asset_type.value} rotation with an empty cache. This indicates wrong logic.")
191+
log.warning("Attempted %s rotation with an empty cache. This indicates wrong logic.", asset_type.value)
192192
return False
193193

194194
if len(state) == 1 and 1 in state.values():
195-
log.debug(f"Aborting {asset_type.value} rotation: only 1 asset is available and has already been applied.")
195+
log.debug("Aborting %s rotation: only 1 asset is available and has already been applied.", asset_type.value)
196196
return False
197197

198198
current_iteration = min(state.values()) # Choose iteration to draw from.
@@ -219,7 +219,7 @@ async def maybe_rotate_assets(self, asset_type: AssetType) -> None:
219219
is work to be done before the timestamp is read and written, the next read will likely commence slightly
220220
under 24 hours after the last write.
221221
"""
222-
log.debug(f"Checking whether it's time for {asset_type.value}s to rotate.")
222+
log.debug("Checking whether it's time for %ss to rotate.", asset_type.value)
223223

224224
last_rotation_timestamp = await self.cache_information.get(f"last_{asset_type.value}_rotation_timestamp")
225225

@@ -245,7 +245,7 @@ async def initiate_rotation(self, asset_type: AssetType, available_assets: list[
245245
246246
This function does not upload a new asset!
247247
"""
248-
log.debug(f"Initiating new {asset_type.value} rotation.")
248+
log.debug("Initiating new %s rotation.", asset_type.value)
249249

250250
await self.asset_caches[asset_type].clear()
251251

@@ -265,13 +265,17 @@ async def send_info_embed(self, channel_id: int, *, is_notification: bool) -> No
265265
We read event information from `cache_information`. The caller is therefore responsible for making
266266
sure that the cache is up-to-date before calling this function.
267267
"""
268-
log.debug(f"Sending event information event to channel: {channel_id} ({is_notification=}).")
268+
log.debug(
269+
"Sending event information event to channel: %s (is_notification=%r).",
270+
channel_id,
271+
is_notification,
272+
)
269273

270274
await self.bot.wait_until_guild_available()
271275
channel: discord.TextChannel | None = self.bot.get_channel(channel_id)
272276

273277
if channel is None:
274-
log.warning(f"Cannot send event information: channel {channel_id} not found!")
278+
log.warning("Cannot send event information: channel %s not found!", channel_id)
275279
return
276280

277281
log.trace(f"Destination channel: #{channel.name}.")
@@ -304,7 +308,7 @@ async def enter_event(self, event: Event) -> tuple[bool, bool]:
304308
305309
Return a 2-tuple indicating whether the banner, and the icon, were applied successfully.
306310
"""
307-
log.info(f"Entering event: '{event.path}'.")
311+
log.info("Entering event: '%s'.", event.path)
308312

309313
# Prepare and apply new icon and banner rotations
310314
await self.initiate_rotation(AssetType.ICON, event.icons)
@@ -571,7 +575,7 @@ async def branding_calendar_group(self, ctx: commands.Context) -> None:
571575
first_25 = list(available_events.items())[:25]
572576

573577
if len(first_25) != len(available_events): # Alert core devs that a paginating solution is now necessary.
574-
log.warning(f"There are {len(available_events)} events, but the calendar view can only display 25.")
578+
log.warning("There are %s events, but the calendar view can only display 25.", len(available_events))
575579

576580
for name, duration in first_25:
577581
embed.add_field(name=name[:256], value=duration[:1024])

bot/exts/backend/branding/_repository.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ async def fetch_directory(self, path: str, types: t.Container[str] = ("file", "d
136136
Passing custom `types` allows getting only files or directories. By default, both are included.
137137
"""
138138
full_url = f"{BRANDING_URL}/{path}"
139-
log.debug(f"Fetching directory from branding repository: '{full_url}'.")
139+
log.debug("Fetching directory from branding repository: '%s'.", full_url)
140140

141141
async with self.bot.http_session.get(full_url, params=PARAMS, headers=HEADERS) as response:
142142
_raise_for_status(response)
@@ -151,7 +151,7 @@ async def fetch_file(self, download_url: str) -> bytes:
151151
152152
Raise an exception if the request does not succeed.
153153
"""
154-
log.debug(f"Fetching file from branding repository: '{download_url}'.")
154+
log.debug("Fetching file from branding repository: '%s'.", download_url)
155155

156156
async with self.bot.http_session.get(download_url, params=PARAMS, headers=HEADERS) as response:
157157
_raise_for_status(response)
@@ -245,7 +245,7 @@ async def get_current_event(self) -> tuple[Event, list[Event]]:
245245
Events are validated in the branding repo. The bot assumes that events are valid.
246246
"""
247247
utc_now = datetime.now(tz=UTC)
248-
log.debug(f"Finding active event for: {utc_now}.")
248+
log.debug("Finding active event for: %s.", utc_now)
249249

250250
# Construct an object in the arbitrary year for the purpose of comparison.
251251
lookup_now = date(year=ARBITRARY_YEAR, month=utc_now.month, day=utc_now.day)

bot/exts/backend/config_verifier.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ async def cog_load(self) -> None:
2929
]
3030

3131
if invalid_channels:
32-
log.warning(f"Configured channels do not exist in server: {invalid_channels}.")
32+
log.warning("Configured channels do not exist in server: %s.", invalid_channels)
3333

3434

3535
async def setup(bot: Bot) -> None:

bot/exts/backend/error_handler.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -370,7 +370,7 @@ async def handle_check_failure(ctx: Context, e: errors.CheckFailure) -> None:
370370
async def handle_api_error(ctx: Context, e: ResponseCodeError) -> None:
371371
"""Send an error message in `ctx` for ResponseCodeError and log it."""
372372
if e.status == 404:
373-
log.debug(f"API responded with 404 for command {ctx.command}")
373+
log.debug("API responded with 404 for command %s", ctx.command)
374374
await ctx.send("There does not seem to be anything matching your query.")
375375
ctx.bot.stats.incr("errors.api_error_404")
376376
elif e.status == 400:
@@ -382,11 +382,11 @@ async def handle_api_error(ctx: Context, e: ResponseCodeError) -> None:
382382
await ctx.send("According to the API, your request is malformed.")
383383
ctx.bot.stats.incr("errors.api_error_400")
384384
elif 500 <= e.status < 600:
385-
log.warning(f"API responded with {e.status} for command {ctx.command}")
385+
log.warning("API responded with %s for command %s", e.status, ctx.command)
386386
await ctx.send("Sorry, there seems to be an internal issue with the API.")
387387
ctx.bot.stats.incr("errors.api_internal_server_error")
388388
else:
389-
log.warning(f"Unexpected API response for command {ctx.command}: {e.status}")
389+
log.warning("Unexpected API response for command %s: %s", ctx.command, e.status)
390390
await ctx.send(f"Got an unexpected status code from the API (`{e.status}`).")
391391
ctx.bot.stats.incr(f"errors.api_error_{e.status}")
392392

@@ -418,7 +418,7 @@ async def handle_unexpected_error(ctx: Context, e: errors.CommandError) -> None:
418418
f"https://discordapp.com/channels/{ctx.guild.id}/{ctx.channel.id}/{ctx.message.id}"
419419
)
420420

421-
log.error(f"Error executing command invoked by {ctx.message.author}: {ctx.message.content}", exc_info=e)
421+
log.error("Error executing command invoked by %s: %s", ctx.message.author, ctx.message.content, exc_info=e)
422422

423423

424424
async def setup(bot: Bot) -> None:

bot/exts/backend/sync/_syncers.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ async def sync(cls, guild: Guild, ctx: Context | None = None) -> None:
5252
5353
If `ctx` is given, send a message with the results.
5454
"""
55-
log.info(f"Starting {cls.name} syncer.")
55+
log.info("Starting %s syncer.", cls.name)
5656

5757
if ctx:
5858
message = await ctx.send(f"📊 Synchronising {cls.name}s.")
@@ -63,7 +63,7 @@ async def sync(cls, guild: Guild, ctx: Context | None = None) -> None:
6363
try:
6464
await cls._sync(diff)
6565
except ResponseCodeError as e:
66-
log.exception(f"{cls.name} syncer failed!")
66+
log.exception("%s syncer failed!", cls.name)
6767

6868
# Don't show response text because it's probably some really long HTML.
6969
results = f"status {e.status}\n```{e.response_json or 'See log output for details'}```"
@@ -73,7 +73,7 @@ async def sync(cls, guild: Guild, ctx: Context | None = None) -> None:
7373
results = (f"{name} `{len(val)}`" for name, val in diff_dict.items() if val is not None)
7474
results = ", ".join(results)
7575

76-
log.info(f"{cls.name} syncer finished: {results}.")
76+
log.info("%s syncer finished: %s.", cls.name, results)
7777
content = f":ok_hand: Synchronisation of {cls.name}s complete: {results}"
7878

7979
if message:

bot/exts/filtering/_filter_lists/antispam.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def get_filter_type(self, content: str) -> type[UniqueFilter] | None:
5050
return antispam_filter_types[content]
5151
except KeyError:
5252
if content not in self._already_warned:
53-
log.warning(f"An antispam filter named {content} was supplied, but no matching implementation found.")
53+
log.warning("An antispam filter named %s was supplied, but no matching implementation found.", content)
5454
self._already_warned.add(content)
5555
return None
5656

@@ -124,7 +124,7 @@ async def process_deletion_context() -> None:
124124
await asyncio.sleep(ALERT_DELAY)
125125

126126
if member not in self.message_deletion_queue:
127-
log.error(f"Started processing deletion queue for context `{member}`, but it was not found!")
127+
log.error("Started processing deletion queue for context `%s`, but it was not found!", member)
128128
return
129129

130130
deletion_context = self.message_deletion_queue.pop(member)

bot/exts/filtering/_filter_lists/filter_list.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ def _create_filter(self, filter_data: dict, defaults: Defaults) -> T | None:
222222
if filter_type:
223223
return filter_type(filter_data, defaults)
224224
if content not in self._already_warned:
225-
log.warning(f"A filter named {content} was supplied, but no matching implementation found.")
225+
log.warning("A filter named %s was supplied, but no matching implementation found.", content)
226226
self._already_warned.add(content)
227227
return None
228228
except TypeError as e:

bot/exts/filtering/_filters/unique/discord_token.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -188,15 +188,15 @@ def is_valid_timestamp(b64_content: str) -> bool:
188188
decoded_bytes = base64.urlsafe_b64decode(b64_content)
189189
timestamp = int.from_bytes(decoded_bytes, byteorder="big")
190190
except ValueError as e:
191-
log.debug(f"Failed to decode token timestamp '{b64_content}': {e}")
191+
log.debug("Failed to decode token timestamp '%s': %s", b64_content, e)
192192
return False
193193

194194
# Seems like newer tokens don't need the epoch added, but add anyway since an upper bound
195195
# is not checked.
196196
if timestamp + TOKEN_EPOCH >= DISCORD_EPOCH:
197197
return True
198198

199-
log.debug(f"Invalid token timestamp '{b64_content}': smaller than Discord epoch")
199+
log.debug("Invalid token timestamp '%s': smaller than Discord epoch", b64_content)
200200
return False
201201

202202
@staticmethod
@@ -210,8 +210,10 @@ def is_maybe_valid_hmac(b64_content: str) -> bool:
210210
unique = len(set(b64_content.lower()))
211211
if unique <= 3:
212212
log.debug(
213-
f"Considering the HMAC {b64_content} a dummy because it has {unique}"
214-
" case-insensitively unique characters"
213+
"Considering the HMAC %s a dummy because it has %s"
214+
" case-insensitively unique characters",
215+
b64_content,
216+
unique,
215217
)
216218
return False
217219
return True

0 commit comments

Comments
 (0)