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 return matrix_to_zulip
async def _matrix_to_zulip(self, room: nio.MatrixRoom, event: nio.Event) -> None: 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 # 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. # 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)) raise Bridge_FatalMatrixException(str(result))
def _zulip_to_matrix(self, msg: Dict[str, Any]) -> None: 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) room_id: Optional[str] = self.get_matrix_room_for_zulip_message(msg)
if room_id is None: 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: for key in zulip_bridge_key_set:
first_bridge[key] = section_config[key] first_bridge[key] = section_config[key]
else: else:
logging.warning(f"Unknown section {section}") logging.warning("Unknown section %s", section)
# Add the "first_bridge" to the bridges. # Add the "first_bridge" to the bridges.
zulip_target = (first_bridge["stream"], first_bridge["topic"]) 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) sys.exit(-1)
else: else:
logging.warning( 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 return None
@ -252,7 +252,7 @@ def handle_event(event: Dict[str, Any]) -> None:
elif event_type == "sprint_ended": elif event_type == "sprint_ended":
logging.warning("Sprint notifications not yet implemented") logging.warning("Sprint notifications not yet implemented")
else: else:
logging.info(f"Unknown event type {event_type}, ignoring!") logging.info("Unknown event type %s, ignoring!", event_type)
if subject and content: if subject and content:
if len(subject) > 60: if len(subject) > 60:
@ -281,8 +281,8 @@ def run_mirror() -> None:
since = default_since() since = default_since()
else: else:
since = datetime.fromtimestamp(float(timestamp), tz=pytz.utc) since = datetime.fromtimestamp(float(timestamp), tz=pytz.utc)
except (ValueError, OSError) as e: except (ValueError, OSError):
logging.warning(f"Could not open resume file: {e}") logging.warning("Could not open resume file", exc_info=True)
since = default_since() since = default_since()
try: try:

View file

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

View file

@ -176,7 +176,7 @@ for tries in range(10):
missing = 0 missing = 0
for elt in zephyr_subs_to_add: for elt in zephyr_subs_to_add:
if elt not in zephyr_subs: if elt not in zephyr_subs:
logging.error(f"Failed to subscribe to {elt}") logging.error("Failed to subscribe to %s", elt)
missing += 1 missing += 1
if missing == 0: if missing == 0:
actually_subscribed = True actually_subscribed = True
@ -250,11 +250,11 @@ for key, (stream, test) in zhkeys.items():
server_failure_again = send_zephyr(zwrite_args, str(new_key)) server_failure_again = send_zephyr(zwrite_args, str(new_key))
if server_failure_again: if server_failure_again:
logging.error( 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) print_status_and_exit(1)
else: 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()
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"]) message["content"] = unwrap_lines(zeph["content"])
if options.test_mode and options.site == DEFAULT_SITE: 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 {"result": "success"}
return zulip_client.send_message(message) 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 # retrying the next time the bot checks its subscriptions are
# up to date. # up to date.
logger.exception("Error subscribing to streams (will retry automatically):") 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 return
try: try:
@ -224,7 +224,7 @@ def zephyr_bulk_subscribe(subs: List[Tuple[str, str, str]]) -> None:
for cls, instance, recipient in subs: for cls, instance, recipient in subs:
if cls not in actual_zephyr_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 # We'll retry automatically when we next check for
# streams to subscribe to (within 15 seconds), but # streams to subscribe to (within 15 seconds), but
# it's worth doing 1 retry immediately to avoid # it's worth doing 1 retry immediately to avoid
@ -473,7 +473,7 @@ def process_notice(
if is_personal and not options.forward_personals: if is_personal and not options.forward_personals:
return return
if (zephyr_class.lower() not in current_zephyr_subs) and not is_personal: 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 return
if notice.z_default_format.startswith(b"Zephyr error: See") or notice.z_default_format.endswith( if notice.z_default_format.startswith(b"Zephyr error: See") or notice.z_default_format.endswith(
b"@(@color(blue))" b"@(@color(blue))"
@ -541,7 +541,9 @@ def process_notice(
heading = "" heading = ""
zeph["content"] = heading + zeph["content"] 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: if log is not None:
log.write(json.dumps(zeph) + "\n") log.write(json.dumps(zeph) + "\n")
log.flush() log.flush()
@ -555,7 +557,7 @@ def send_zulip_worker(zulip_queue: "Queue[ZephyrDict]", zulip_client: zulip.Clie
try: try:
res = send_zulip(zulip_client, zeph) res = send_zulip(zulip_client, zeph)
if res.get("result") != "success": 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: except Exception:
logger.exception("Error relaying zephyr:") logger.exception("Error relaying zephyr:")
zulip_queue.task_done() zulip_queue.task_done()
@ -800,7 +802,7 @@ Feedback button or at support@zulip.com."""
instance = zephyr_class instance = zephyr_class
zephyr_class = "message" zephyr_class = "message"
zwrite_args.extend(["-c", zephyr_class, "-i", instance]) 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": elif message["type"] == "private":
if len(message["display_recipient"]) == 1: if len(message["display_recipient"]) == 1:
recipient = to_zephyr_username(message["display_recipient"][0]["email"]) 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", "") to_zephyr_username(user["email"]).replace("@ATHENA.MIT.EDU", "")
for user in message["display_recipient"] for user in message["display_recipient"]
] ]
logger.info(f"Forwarding message to {recipients}") logger.info("Forwarding message to %s", recipients)
zwrite_args.extend(recipients) zwrite_args.extend(recipients)
if message.get("invite_only_stream"): 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"]) zwrite_args.extend(["-O", "crypt"])
if options.test_mode: 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 return
(code, stderr) = send_authed_zephyr(zwrite_args, wrapped_content) (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: for cls, instance, recipient, reason in skipped:
if verbose: if verbose:
if reason != "": if reason != "":
logger.info(f" [{cls},{instance},{recipient}] ({reason})") logger.info(" [%s,%s,%s] (%s)", cls, instance, recipient, reason)
else: else:
logger.info(f" [{cls},{instance},{recipient}]") logger.info(" [%s,%s,%s]", cls, instance, recipient)
if len(skipped) > 0: if len(skipped) > 0:
if verbose: if verbose:
logger.info( logger.info(
@ -1108,11 +1110,11 @@ def parse_zephyr_subs(verbose: bool = False) -> Set[Tuple[str, str, str]]:
recipient = recipient.replace("%me%", options.user) recipient = recipient.replace("%me%", options.user)
if not valid_stream_name(cls): if not valid_stream_name(cls):
if verbose: if verbose:
logger.error(f"Skipping subscription to unsupported class name: [{line}]") logger.error("Skipping subscription to unsupported class name: [%s]", line)
continue continue
except Exception: except Exception:
if verbose: if verbose:
logger.error(f"Couldn't parse ~/.zephyr.subs line: [{line}]") logger.error("Couldn't parse ~/.zephyr.subs line: [%s]", line)
continue continue
zephyr_subscriptions.add((cls.strip(), instance.strip(), recipient.strip())) zephyr_subscriptions.add((cls.strip(), instance.strip(), recipient.strip()))
return zephyr_subscriptions return zephyr_subscriptions
@ -1311,7 +1313,7 @@ or specify the --api-key-file option."""
continue continue
# Another copy of zephyr_mirror.py! Kill it. # 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: try:
os.kill(pid, signal.SIGINT) os.kill(pid, signal.SIGINT)
except OSError: except OSError:

View file

@ -88,7 +88,7 @@ def query_salesforce(
limit = re_limit.search(raw_arg) limit = re_limit.search(raw_arg)
if limit: if limit:
limit_num = int(limit.group().rsplit(" ", 1)[1]) 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 query = default_query
if "query" in command.keys(): if "query" in command.keys():
query = command["query"] 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") 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!" return "Sorry, I cannot process your request right now, please try again later!"
except XkcdNotFoundError: 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}" return f"Sorry, there is likely no xkcd comic strip with id: #{command}"
else: else:
return "#{}: **{}**\n[{}]({})".format( return "#{}: **{}**\n[{}]({})".format(

View file

@ -226,7 +226,7 @@ class GameAdapter:
if sender not in self.user_cache.keys(): if sender not in self.user_cache.keys():
self.add_user_to_cache(message) 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 self.is_single_player:
if content.lower().startswith("start game with") or content.lower().startswith( 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") req_path = os.path.join(path_to_bot, "requirements.txt")
if os.path.isfile(req_path): if os.path.isfile(req_path):
bot_name = os.path.basename(path_to_bot) 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 # pip install -r $BASEDIR/requirements.txt -t $BASEDIR/bot_dependencies --quiet
rcode = subprocess.call(["pip", "install", "-r", req_path]) rcode = subprocess.call(["pip", "install", "-r", req_path])

View file

@ -90,12 +90,12 @@ def read_config_file(
bot_section = parser.sections()[0] bot_section = parser.sections()[0]
bots_config[bot_name] = read_config_section(parser, bot_section) bots_config[bot_name] = read_config_section(parser, bot_section)
logging.warning( 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:] ignored_sections = parser.sections()[1:]
if len(ignored_sections) > 0: 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 return bots_config