ruff: Fix G004 Logging statement uses f-string.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg 2023-10-28 16:16:56 -07:00
parent d85ace8e7e
commit 6b2861c3ec
10 changed files with 36 additions and 32 deletions

View file

@ -91,7 +91,7 @@ class MatrixToZulip:
return matrix_to_zulip
async def _matrix_to_zulip(self, room: nio.MatrixRoom, event: nio.Event) -> None:
logging.debug(f"_matrix_to_zulip; room {room.room_id}, event: {event}")
logging.debug("_matrix_to_zulip; room %s, event: %s", room.room_id, event)
# We do this to identify the messages generated from Zulip -> Matrix
# and we make sure we don't forward it again to the Zulip stream.
@ -253,7 +253,7 @@ class ZulipToMatrix:
raise Bridge_FatalMatrixException(str(result))
def _zulip_to_matrix(self, msg: Dict[str, Any]) -> None:
logging.debug(f"_zulip_to_matrix; msg: {msg}")
logging.debug("_zulip_to_matrix; msg: %s", msg)
room_id: Optional[str] = self.get_matrix_room_for_zulip_message(msg)
if room_id is None:
@ -518,7 +518,7 @@ def read_configuration(config_file: str) -> Dict[str, Dict[str, Any]]:
for key in zulip_bridge_key_set:
first_bridge[key] = section_config[key]
else:
logging.warning(f"Unknown section {section}")
logging.warning("Unknown section %s", section)
# Add the "first_bridge" to the bridges.
zulip_target = (first_bridge["stream"], first_bridge["topic"])

View file

@ -76,7 +76,7 @@ def make_api_call(path: str) -> Optional[List[Dict[str, Any]]]:
sys.exit(-1)
else:
logging.warning(
f"Found non-success response status code: {response.status_code} {response.text}"
"Found non-success response status code: %s %s", response.status_code, response.text
)
return None
@ -252,7 +252,7 @@ def handle_event(event: Dict[str, Any]) -> None:
elif event_type == "sprint_ended":
logging.warning("Sprint notifications not yet implemented")
else:
logging.info(f"Unknown event type {event_type}, ignoring!")
logging.info("Unknown event type %s, ignoring!", event_type)
if subject and content:
if len(subject) > 60:
@ -281,8 +281,8 @@ def run_mirror() -> None:
since = default_since()
else:
since = datetime.fromtimestamp(float(timestamp), tz=pytz.utc)
except (ValueError, OSError) as e:
logging.warning(f"Could not open resume file: {e}")
except (ValueError, OSError):
logging.warning("Could not open resume file", exc_info=True)
since = default_since()
try:

View file

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

View file

@ -176,7 +176,7 @@ for tries in range(10):
missing = 0
for elt in zephyr_subs_to_add:
if elt not in zephyr_subs:
logging.error(f"Failed to subscribe to {elt}")
logging.error("Failed to subscribe to %s", elt)
missing += 1
if missing == 0:
actually_subscribed = True
@ -250,11 +250,11 @@ for key, (stream, test) in zhkeys.items():
server_failure_again = send_zephyr(zwrite_args, str(new_key))
if server_failure_again:
logging.error(
f"Zephyr server failure twice in a row on keys {key} and {new_key}! Aborting."
"Zephyr server failure twice in a row on keys %s and %s! Aborting.", key, new_key
)
print_status_and_exit(1)
else:
logging.warning(f"Replaced key {key} with {new_key} due to Zephyr server failure.")
logging.warning("Replaced key %s with %s due to Zephyr server failure.", key, new_key)
receive_zephyrs()
receive_zephyrs()

View file

@ -160,7 +160,7 @@ def send_zulip(zulip_client: zulip.Client, zeph: ZephyrDict) -> Dict[str, Any]:
message["content"] = unwrap_lines(zeph["content"])
if options.test_mode and options.site == DEFAULT_SITE:
logger.debug(f"Message is: {message}")
logger.debug("Message is: %s", message)
return {"result": "success"}
return zulip_client.send_message(message)
@ -204,7 +204,7 @@ def zephyr_bulk_subscribe(subs: List[Tuple[str, str, str]]) -> None:
# retrying the next time the bot checks its subscriptions are
# up to date.
logger.exception("Error subscribing to streams (will retry automatically):")
logger.warning(f"Streams were: {[cls for cls, instance, recipient in subs]}")
logger.warning("Streams were: %r", [cls for cls, instance, recipient in subs])
return
try:
@ -224,7 +224,7 @@ def zephyr_bulk_subscribe(subs: List[Tuple[str, str, str]]) -> None:
for cls, instance, recipient in subs:
if cls not in actual_zephyr_subs:
logger.error(f"Zephyr failed to subscribe us to {cls}; will retry")
logger.error("Zephyr failed to subscribe us to %s; will retry", cls)
# We'll retry automatically when we next check for
# streams to subscribe to (within 15 seconds), but
# it's worth doing 1 retry immediately to avoid
@ -473,7 +473,7 @@ def process_notice(
if is_personal and not options.forward_personals:
return
if (zephyr_class.lower() not in current_zephyr_subs) and not is_personal:
logger.debug(f"Skipping ... {zephyr_class}/{zephyr_instance}/{is_personal}")
logger.debug("Skipping ... %s/%s/%s", zephyr_class, zephyr_instance, is_personal)
return
if notice.z_default_format.startswith(b"Zephyr error: See") or notice.z_default_format.endswith(
b"@(@color(blue))"
@ -541,7 +541,9 @@ def process_notice(
heading = ""
zeph["content"] = heading + zeph["content"]
logger.info(f"Received a message on {zephyr_class}/{zephyr_instance} from {zephyr_sender}...")
logger.info(
"Received a message on %s/%s from %s...", zephyr_class, zephyr_instance, zephyr_sender
)
if log is not None:
log.write(json.dumps(zeph) + "\n")
log.flush()
@ -555,7 +557,7 @@ def send_zulip_worker(zulip_queue: "Queue[ZephyrDict]", zulip_client: zulip.Clie
try:
res = send_zulip(zulip_client, zeph)
if res.get("result") != "success":
logger.error(f"Error relaying zephyr:\n{zeph}\n{res}")
logger.error("Error relaying zephyr:\n%s\n%s", zeph, res)
except Exception:
logger.exception("Error relaying zephyr:")
zulip_queue.task_done()
@ -800,7 +802,7 @@ Feedback button or at support@zulip.com."""
instance = zephyr_class
zephyr_class = "message"
zwrite_args.extend(["-c", zephyr_class, "-i", instance])
logger.info(f"Forwarding message to class {zephyr_class}, instance {instance}")
logger.info("Forwarding message to class %s, instance %s", zephyr_class, instance)
elif message["type"] == "private":
if len(message["display_recipient"]) == 1:
recipient = to_zephyr_username(message["display_recipient"][0]["email"])
@ -820,7 +822,7 @@ Feedback button or at support@zulip.com."""
to_zephyr_username(user["email"]).replace("@ATHENA.MIT.EDU", "")
for user in message["display_recipient"]
]
logger.info(f"Forwarding message to {recipients}")
logger.info("Forwarding message to %s", recipients)
zwrite_args.extend(recipients)
if message.get("invite_only_stream"):
@ -845,7 +847,7 @@ Zulip users (like you) received it, Zephyr users did not.
zwrite_args.extend(["-O", "crypt"])
if options.test_mode:
logger.debug(f"Would have forwarded: {zwrite_args}\n{wrapped_content}")
logger.debug("Would have forwarded: %r\n%s", zwrite_args, wrapped_content)
return
(code, stderr) = send_authed_zephyr(zwrite_args, wrapped_content)
@ -1066,9 +1068,9 @@ Zulip subscription to these lines in ~/.zephyr.subs:
for cls, instance, recipient, reason in skipped:
if verbose:
if reason != "":
logger.info(f" [{cls},{instance},{recipient}] ({reason})")
logger.info(" [%s,%s,%s] (%s)", cls, instance, recipient, reason)
else:
logger.info(f" [{cls},{instance},{recipient}]")
logger.info(" [%s,%s,%s]", cls, instance, recipient)
if len(skipped) > 0:
if verbose:
logger.info(
@ -1108,11 +1110,11 @@ def parse_zephyr_subs(verbose: bool = False) -> Set[Tuple[str, str, str]]:
recipient = recipient.replace("%me%", options.user)
if not valid_stream_name(cls):
if verbose:
logger.error(f"Skipping subscription to unsupported class name: [{line}]")
logger.error("Skipping subscription to unsupported class name: [%s]", line)
continue
except Exception:
if verbose:
logger.error(f"Couldn't parse ~/.zephyr.subs line: [{line}]")
logger.error("Couldn't parse ~/.zephyr.subs line: [%s]", line)
continue
zephyr_subscriptions.add((cls.strip(), instance.strip(), recipient.strip()))
return zephyr_subscriptions
@ -1311,7 +1313,7 @@ or specify the --api-key-file option."""
continue
# Another copy of zephyr_mirror.py! Kill it.
logger.info(f"Killing duplicate zephyr_mirror process {pid}")
logger.info("Killing duplicate zephyr_mirror process %d", pid)
try:
os.kill(pid, signal.SIGINT)
except OSError:

View file

@ -88,7 +88,7 @@ def query_salesforce(
limit = re_limit.search(raw_arg)
if limit:
limit_num = int(limit.group().rsplit(" ", 1)[1])
logging.info(f"Searching with limit {limit_num}")
logging.info("Searching with limit %d", limit_num)
query = default_query
if "query" in command.keys():
query = command["query"]

View file

@ -84,7 +84,9 @@ def get_xkcd_bot_response(message: Dict[str, str], quoted_name: str) -> str:
logging.exception("Connection error occurred when trying to connect to xkcd server")
return "Sorry, I cannot process your request right now, please try again later!"
except XkcdNotFoundError:
logging.exception(f"XKCD server responded 404 when trying to fetch comic with id {command}")
logging.exception(
"XKCD server responded 404 when trying to fetch comic with id %s", command
)
return f"Sorry, there is likely no xkcd comic strip with id: #{command}"
else:
return "#{}: **{}**\n[{}]({})".format(

View file

@ -226,7 +226,7 @@ class GameAdapter:
if sender not in self.user_cache.keys():
self.add_user_to_cache(message)
logging.info(f"Added {sender} to user cache")
logging.info("Added %s to user cache", sender)
if self.is_single_player:
if content.lower().startswith("start game with") or content.lower().startswith(

View file

@ -21,7 +21,7 @@ def provision_bot(path_to_bot: str, force: bool) -> None:
req_path = os.path.join(path_to_bot, "requirements.txt")
if os.path.isfile(req_path):
bot_name = os.path.basename(path_to_bot)
logging.info(f"Installing dependencies for {bot_name}...")
logging.info("Installing dependencies for %s...", bot_name)
# pip install -r $BASEDIR/requirements.txt -t $BASEDIR/bot_dependencies --quiet
rcode = subprocess.call(["pip", "install", "-r", req_path])

View file

@ -90,12 +90,12 @@ def read_config_file(
bot_section = parser.sections()[0]
bots_config[bot_name] = read_config_section(parser, bot_section)
logging.warning(
f"First bot name in the config list was changed from '{bot_section}' to '{bot_name}'"
"First bot name in the config list was changed from %r to %r", bot_section, bot_name
)
ignored_sections = parser.sections()[1:]
if len(ignored_sections) > 0:
logging.warning(f"Sections except the '{bot_section}' will be ignored")
logging.warning("Sections except the %r will be ignored", bot_section)
return bots_config