Skip to content

Commit 6b2861c

Browse files
committed
ruff: Fix G004 Logging statement uses f-string.
Signed-off-by: Anders Kaseorg <[email protected]>
1 parent d85ace8 commit 6b2861c

File tree

10 files changed

+36
-32
lines changed

10 files changed

+36
-32
lines changed

zulip/integrations/bridge_with_matrix/matrix_bridge.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ async def create(
9191
return matrix_to_zulip
9292

9393
async def _matrix_to_zulip(self, room: nio.MatrixRoom, event: nio.Event) -> None:
94-
logging.debug(f"_matrix_to_zulip; room {room.room_id}, event: {event}")
94+
logging.debug("_matrix_to_zulip; room %s, event: %s", room.room_id, event)
9595

9696
# We do this to identify the messages generated from Zulip -> Matrix
9797
# and we make sure we don't forward it again to the Zulip stream.
@@ -253,7 +253,7 @@ def _matrix_send(self, **kwargs: Any) -> None:
253253
raise Bridge_FatalMatrixException(str(result))
254254

255255
def _zulip_to_matrix(self, msg: Dict[str, Any]) -> None:
256-
logging.debug(f"_zulip_to_matrix; msg: {msg}")
256+
logging.debug("_zulip_to_matrix; msg: %s", msg)
257257

258258
room_id: Optional[str] = self.get_matrix_room_for_zulip_message(msg)
259259
if room_id is None:
@@ -518,7 +518,7 @@ def read_configuration(config_file: str) -> Dict[str, Dict[str, Any]]:
518518
for key in zulip_bridge_key_set:
519519
first_bridge[key] = section_config[key]
520520
else:
521-
logging.warning(f"Unknown section {section}")
521+
logging.warning("Unknown section %s", section)
522522

523523
# Add the "first_bridge" to the bridges.
524524
zulip_target = (first_bridge["stream"], first_bridge["topic"])

zulip/integrations/codebase/zulip_codebase_mirror

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ def make_api_call(path: str) -> Optional[List[Dict[str, Any]]]:
7676
sys.exit(-1)
7777
else:
7878
logging.warning(
79-
f"Found non-success response status code: {response.status_code} {response.text}"
79+
"Found non-success response status code: %s %s", response.status_code, response.text
8080
)
8181
return None
8282

@@ -252,7 +252,7 @@ def handle_event(event: Dict[str, Any]) -> None:
252252
elif event_type == "sprint_ended":
253253
logging.warning("Sprint notifications not yet implemented")
254254
else:
255-
logging.info(f"Unknown event type {event_type}, ignoring!")
255+
logging.info("Unknown event type %s, ignoring!", event_type)
256256

257257
if subject and content:
258258
if len(subject) > 60:
@@ -281,8 +281,8 @@ def run_mirror() -> None:
281281
since = default_since()
282282
else:
283283
since = datetime.fromtimestamp(float(timestamp), tz=pytz.utc)
284-
except (ValueError, OSError) as e:
285-
logging.warning(f"Could not open resume file: {e}")
284+
except (ValueError, OSError):
285+
logging.warning("Could not open resume file", exc_info=True)
286286
since = default_since()
287287

288288
try:

zulip/integrations/rss/rss-bot

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -244,8 +244,8 @@ for feed_url in feed_urls:
244244

245245
response: Dict[str, Any] = send_zulip(entry, feed_name)
246246
if response["result"] != "success":
247-
logger.error(f"Error processing {feed_url}")
248-
logger.error(str(response))
247+
logger.error("Error processing %s", feed_url)
248+
logger.error("%s", response)
249249
if first_message:
250250
# This is probably some fundamental problem like the stream not
251251
# existing or something being misconfigured, so bail instead of

zulip/integrations/zephyr/check-mirroring

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ for tries in range(10):
176176
missing = 0
177177
for elt in zephyr_subs_to_add:
178178
if elt not in zephyr_subs:
179-
logging.error(f"Failed to subscribe to {elt}")
179+
logging.error("Failed to subscribe to %s", elt)
180180
missing += 1
181181
if missing == 0:
182182
actually_subscribed = True
@@ -250,11 +250,11 @@ for key, (stream, test) in zhkeys.items():
250250
server_failure_again = send_zephyr(zwrite_args, str(new_key))
251251
if server_failure_again:
252252
logging.error(
253-
f"Zephyr server failure twice in a row on keys {key} and {new_key}! Aborting."
253+
"Zephyr server failure twice in a row on keys %s and %s! Aborting.", key, new_key
254254
)
255255
print_status_and_exit(1)
256256
else:
257-
logging.warning(f"Replaced key {key} with {new_key} due to Zephyr server failure.")
257+
logging.warning("Replaced key %s with %s due to Zephyr server failure.", key, new_key)
258258
receive_zephyrs()
259259

260260
receive_zephyrs()

zulip/integrations/zephyr/zephyr_mirror_backend.py

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ def send_zulip(zulip_client: zulip.Client, zeph: ZephyrDict) -> Dict[str, Any]:
160160
message["content"] = unwrap_lines(zeph["content"])
161161

162162
if options.test_mode and options.site == DEFAULT_SITE:
163-
logger.debug(f"Message is: {message}")
163+
logger.debug("Message is: %s", message)
164164
return {"result": "success"}
165165

166166
return zulip_client.send_message(message)
@@ -204,7 +204,7 @@ def zephyr_bulk_subscribe(subs: List[Tuple[str, str, str]]) -> None:
204204
# retrying the next time the bot checks its subscriptions are
205205
# up to date.
206206
logger.exception("Error subscribing to streams (will retry automatically):")
207-
logger.warning(f"Streams were: {[cls for cls, instance, recipient in subs]}")
207+
logger.warning("Streams were: %r", [cls for cls, instance, recipient in subs])
208208
return
209209

210210
try:
@@ -224,7 +224,7 @@ def zephyr_bulk_subscribe(subs: List[Tuple[str, str, str]]) -> None:
224224

225225
for cls, instance, recipient in subs:
226226
if cls not in actual_zephyr_subs:
227-
logger.error(f"Zephyr failed to subscribe us to {cls}; will retry")
227+
logger.error("Zephyr failed to subscribe us to %s; will retry", cls)
228228
# We'll retry automatically when we next check for
229229
# streams to subscribe to (within 15 seconds), but
230230
# it's worth doing 1 retry immediately to avoid
@@ -473,7 +473,7 @@ def process_notice(
473473
if is_personal and not options.forward_personals:
474474
return
475475
if (zephyr_class.lower() not in current_zephyr_subs) and not is_personal:
476-
logger.debug(f"Skipping ... {zephyr_class}/{zephyr_instance}/{is_personal}")
476+
logger.debug("Skipping ... %s/%s/%s", zephyr_class, zephyr_instance, is_personal)
477477
return
478478
if notice.z_default_format.startswith(b"Zephyr error: See") or notice.z_default_format.endswith(
479479
b"@(@color(blue))"
@@ -541,7 +541,9 @@ def process_notice(
541541
heading = ""
542542
zeph["content"] = heading + zeph["content"]
543543

544-
logger.info(f"Received a message on {zephyr_class}/{zephyr_instance} from {zephyr_sender}...")
544+
logger.info(
545+
"Received a message on %s/%s from %s...", zephyr_class, zephyr_instance, zephyr_sender
546+
)
545547
if log is not None:
546548
log.write(json.dumps(zeph) + "\n")
547549
log.flush()
@@ -555,7 +557,7 @@ def send_zulip_worker(zulip_queue: "Queue[ZephyrDict]", zulip_client: zulip.Clie
555557
try:
556558
res = send_zulip(zulip_client, zeph)
557559
if res.get("result") != "success":
558-
logger.error(f"Error relaying zephyr:\n{zeph}\n{res}")
560+
logger.error("Error relaying zephyr:\n%s\n%s", zeph, res)
559561
except Exception:
560562
logger.exception("Error relaying zephyr:")
561563
zulip_queue.task_done()
@@ -800,7 +802,7 @@ def forward_to_zephyr(message: Dict[str, Any], zulip_client: zulip.Client) -> No
800802
instance = zephyr_class
801803
zephyr_class = "message"
802804
zwrite_args.extend(["-c", zephyr_class, "-i", instance])
803-
logger.info(f"Forwarding message to class {zephyr_class}, instance {instance}")
805+
logger.info("Forwarding message to class %s, instance %s", zephyr_class, instance)
804806
elif message["type"] == "private":
805807
if len(message["display_recipient"]) == 1:
806808
recipient = to_zephyr_username(message["display_recipient"][0]["email"])
@@ -820,7 +822,7 @@ def forward_to_zephyr(message: Dict[str, Any], zulip_client: zulip.Client) -> No
820822
to_zephyr_username(user["email"]).replace("@ATHENA.MIT.EDU", "")
821823
for user in message["display_recipient"]
822824
]
823-
logger.info(f"Forwarding message to {recipients}")
825+
logger.info("Forwarding message to %s", recipients)
824826
zwrite_args.extend(recipients)
825827

826828
if message.get("invite_only_stream"):
@@ -845,7 +847,7 @@ class and your mirroring bot does not have access to the relevant \
845847
zwrite_args.extend(["-O", "crypt"])
846848

847849
if options.test_mode:
848-
logger.debug(f"Would have forwarded: {zwrite_args}\n{wrapped_content}")
850+
logger.debug("Would have forwarded: %r\n%s", zwrite_args, wrapped_content)
849851
return
850852

851853
(code, stderr) = send_authed_zephyr(zwrite_args, wrapped_content)
@@ -1066,9 +1068,9 @@ def add_zulip_subscriptions(verbose: bool) -> None:
10661068
for cls, instance, recipient, reason in skipped:
10671069
if verbose:
10681070
if reason != "":
1069-
logger.info(f" [{cls},{instance},{recipient}] ({reason})")
1071+
logger.info(" [%s,%s,%s] (%s)", cls, instance, recipient, reason)
10701072
else:
1071-
logger.info(f" [{cls},{instance},{recipient}]")
1073+
logger.info(" [%s,%s,%s]", cls, instance, recipient)
10721074
if len(skipped) > 0:
10731075
if verbose:
10741076
logger.info(
@@ -1108,11 +1110,11 @@ def parse_zephyr_subs(verbose: bool = False) -> Set[Tuple[str, str, str]]:
11081110
recipient = recipient.replace("%me%", options.user)
11091111
if not valid_stream_name(cls):
11101112
if verbose:
1111-
logger.error(f"Skipping subscription to unsupported class name: [{line}]")
1113+
logger.error("Skipping subscription to unsupported class name: [%s]", line)
11121114
continue
11131115
except Exception:
11141116
if verbose:
1115-
logger.error(f"Couldn't parse ~/.zephyr.subs line: [{line}]")
1117+
logger.error("Couldn't parse ~/.zephyr.subs line: [%s]", line)
11161118
continue
11171119
zephyr_subscriptions.add((cls.strip(), instance.strip(), recipient.strip()))
11181120
return zephyr_subscriptions
@@ -1311,7 +1313,7 @@ def die_gracefully(signal: int, frame: Optional[FrameType]) -> None:
13111313
continue
13121314

13131315
# Another copy of zephyr_mirror.py! Kill it.
1314-
logger.info(f"Killing duplicate zephyr_mirror process {pid}")
1316+
logger.info("Killing duplicate zephyr_mirror process %d", pid)
13151317
try:
13161318
os.kill(pid, signal.SIGINT)
13171319
except OSError:

zulip_bots/zulip_bots/bots/salesforce/salesforce.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ def query_salesforce(
8888
limit = re_limit.search(raw_arg)
8989
if limit:
9090
limit_num = int(limit.group().rsplit(" ", 1)[1])
91-
logging.info(f"Searching with limit {limit_num}")
91+
logging.info("Searching with limit %d", limit_num)
9292
query = default_query
9393
if "query" in command.keys():
9494
query = command["query"]

zulip_bots/zulip_bots/bots/xkcd/xkcd.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,9 @@ def get_xkcd_bot_response(message: Dict[str, str], quoted_name: str) -> str:
8484
logging.exception("Connection error occurred when trying to connect to xkcd server")
8585
return "Sorry, I cannot process your request right now, please try again later!"
8686
except XkcdNotFoundError:
87-
logging.exception(f"XKCD server responded 404 when trying to fetch comic with id {command}")
87+
logging.exception(
88+
"XKCD server responded 404 when trying to fetch comic with id %s", command
89+
)
8890
return f"Sorry, there is likely no xkcd comic strip with id: #{command}"
8991
else:
9092
return "#{}: **{}**\n[{}]({})".format(

zulip_bots/zulip_bots/game_handler.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ def handle_message(self, message: Dict[str, Any], bot_handler: BotHandler) -> No
226226

227227
if sender not in self.user_cache.keys():
228228
self.add_user_to_cache(message)
229-
logging.info(f"Added {sender} to user cache")
229+
logging.info("Added %s to user cache", sender)
230230

231231
if self.is_single_player:
232232
if content.lower().startswith("start game with") or content.lower().startswith(

zulip_bots/zulip_bots/provision.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def provision_bot(path_to_bot: str, force: bool) -> None:
2121
req_path = os.path.join(path_to_bot, "requirements.txt")
2222
if os.path.isfile(req_path):
2323
bot_name = os.path.basename(path_to_bot)
24-
logging.info(f"Installing dependencies for {bot_name}...")
24+
logging.info("Installing dependencies for %s...", bot_name)
2525

2626
# pip install -r $BASEDIR/requirements.txt -t $BASEDIR/bot_dependencies --quiet
2727
rcode = subprocess.call(["pip", "install", "-r", req_path])

zulip_botserver/zulip_botserver/server.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,12 +90,12 @@ def read_config_file(
9090
bot_section = parser.sections()[0]
9191
bots_config[bot_name] = read_config_section(parser, bot_section)
9292
logging.warning(
93-
f"First bot name in the config list was changed from '{bot_section}' to '{bot_name}'"
93+
"First bot name in the config list was changed from %r to %r", bot_section, bot_name
9494
)
9595
ignored_sections = parser.sections()[1:]
9696

9797
if len(ignored_sections) > 0:
98-
logging.warning(f"Sections except the '{bot_section}' will be ignored")
98+
logging.warning("Sections except the %r will be ignored", bot_section)
9999

100100
return bots_config
101101

0 commit comments

Comments
 (0)