Skip to content

Commit

Permalink
Change f-string to % in loggings for performance reasons (#1683)
Browse files Browse the repository at this point in the history
* change f-string to % in loggings

* fix lint
  • Loading branch information
nilupulmanodya authored Mar 6, 2023
1 parent b83879f commit 7ff05ed
Show file tree
Hide file tree
Showing 12 changed files with 48 additions and 46 deletions.
10 changes: 5 additions & 5 deletions mslib/mscolab/seed.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def add_all_users_default_operation(path='TEMPLATE', description="Operation to k
return True
except IntegrityError as err:
db.session.rollback()
logging.debug(f"Error writing to db: {err}")
logging.debug("Error writing to db: %s", err)
db.session.close()


Expand All @@ -98,7 +98,7 @@ def delete_user(email):
with app.app_context():
user = User.query.filter_by(emailid=str(email)).first()
if user:
logging.info(f"User: {email} deleted from db")
logging.info("User: %s deleted from db", email)
db.session.delete(user)
db.session.commit()
db.session.close()
Expand Down Expand Up @@ -126,11 +126,11 @@ def add_user(email, username, password):
db.session.add(db_user)
db.session.commit()
db.session.close()
logging.info(f"Userdata: {email} {username} {password}")
logging.info("Userdata: %s %s %s", email, username, password)
logging.info(template)
return True
else:
logging.info(f"{user_name_exists} already in db")
logging.info("%s already in db", user_name_exists)
return False


Expand Down Expand Up @@ -199,7 +199,7 @@ def add_user_to_operation(path=None, access_level='admin', emailid=None):
return True
except IntegrityError as err:
db.session.rollback()
logging.debug(f"Error writing to db: {err}")
logging.debug("Error writing to db: %s", err)
db.session.close()
return False

Expand Down
2 changes: 1 addition & 1 deletion mslib/mscolab/sockets_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ def handle_file_save(self, json_req):
# emit file-changed event to trigger reload of flight track
socketio.emit('file-changed', json.dumps({"op_id": op_id, "u_id": user.id}))
else:
logging.debug(f'login expired for {user.username}, state unauthorized!')
logging.debug("login expired for %s, state unauthorized!", user.username)

def emit_file_change(self, op_id):
socketio.emit('file-changed', json.dumps({"op_id": op_id}))
Expand Down
4 changes: 2 additions & 2 deletions mslib/mscolab/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,9 @@ def os_fs_create_dir(dir):
try:
_ = fs.open_fs(dir)
except fs.errors.CreateFailed:
logging.error(f'Make sure that the FS url "{dir}" exists')
logging.error('Make sure that the FS url "%s" exists', dir)
except fs.opener.errors.UnsupportedProtocol:
logging.error(f'FS url "{dir}" not supported')
logging.error('FS url "%s" not supported', dir)
else:
_dir = os.path.expanduser(dir)
if not os.path.exists(_dir):
Expand Down
10 changes: 5 additions & 5 deletions mslib/msui/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
except fs.errors.CreateFailed:
_fs.makedirs(MSUI_CONFIG_PATH)
except fs.opener.errors.UnsupportedProtocol:
logging.error(f'FS url "{MSUI_CONFIG_PATH}" not supported')
logging.error('FS url "%s" not supported', MSUI_CONFIG_PATH)
else:
_dir = os.path.expanduser(MSUI_CONFIG_PATH)
if not os.path.exists(_dir):
Expand All @@ -60,14 +60,14 @@
with _fs.open(file_name, 'w') as fid:
fid.write("{}")
except fs.errors.CreateFailed:
logging.error(f'"{MSUI_SETTINGS}" can''t be created')
logging.error('"%s" can''t be created', MSUI_SETTINGS)
else:
if not os.path.exists(MSUI_SETTINGS):
try:
with open(MSUI_SETTINGS, 'w') as fid:
fid.write("{}")
except IOError:
logging.error(f'"{MSUI_SETTINGS}" can''t be created')
logging.error('"%s" can''t be created', MSUI_SETTINGS)

# ToDo refactor to a function
MSS_AUTOPLOT = os.getenv('MSS_AUTOPLOT', os.path.join(MSUI_CONFIG_PATH, "mssautoplot.json"))
Expand All @@ -82,14 +82,14 @@
with _fs.open(file_name, 'w') as fid:
fid.write("{}")
except fs.errors.CreateFailed:
logging.error(f'"{MSS_AUTOPLOT}" can''t be created')
logging.error('"%s" can''t be created', MSS_AUTOPLOT)
else:
if not os.path.exists(MSS_AUTOPLOT):
try:
with open(MSS_AUTOPLOT, 'w') as fid:
fid.write("{}")
except IOError:
logging.error(f'"{MSS_AUTOPLOT}" can''t be created')
logging.error('"%s" can''t be created', MSS_AUTOPLOT)

WMS_LOGIN_CACHE = {}
MSC_LOGIN_CACHE = {}
Expand Down
14 changes: 7 additions & 7 deletions mslib/msui/editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ def add_option_handler(self):
self.view.scrollTo(proxy_index)
self.view.selectionModel().select(
proxy_index, QtCore.QItemSelectionModel.ClearAndSelect | QtCore.QItemSelectionModel.Rows)
logging.debug(f"Added new value for {option}")
logging.debug("Added new value for %s", option)
self.update_view()
break

Expand Down Expand Up @@ -442,7 +442,7 @@ def remove_option_handler(self):
# ToDo add confirmation dialog here

options = "\n".join([index.data() for index in removable_indexes])
logging.debug(f"Attempting to remove the following options\n{options}")
logging.debug("Attempting to remove the following options\n%s", options)

self.view.selectionModel().clearSelection()
for index in removable_indexes:
Expand Down Expand Up @@ -499,7 +499,7 @@ def update(data, option, value):
# ToDo add confirmation dialog here

options = "\n".join([index.data() for index in selected_indexes])
logging.debug(f"Attempting to restore defaults for the following options\n{options}")
logging.debug("Attempting to restore defaults for the following options\n%s", options)

for index in selected_indexes:
# check if root option and present in mss_default.key_value_options
Expand Down Expand Up @@ -557,11 +557,11 @@ def import_config(self):
json_file_data = json.loads(file_content, object_pairs_hook=dict_raise_on_duplicates_empty)
except json.JSONDecodeError as e:
show_popup(self, "Error while loading file", e)
logging.error(f"Error while loading json file {e}")
logging.error("Error while loading json file %s", e)
return
except ValueError as e:
show_popup(self, "Invalid keys detected", e)
logging.error(f"Error while loading json file {e}")
logging.error("Error while loading json file %s", e)
return

if json_file_data:
Expand Down Expand Up @@ -679,15 +679,15 @@ def save_config(self):
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
QtWidgets.QMessageBox.No)
if ret == QtWidgets.QMessageBox.Yes:
logging.debug(f"saving config file to: {self.path} and restarting MSS")
logging.debug("saving config file to: %s and restarting MSS", self.path)
self._save_to_path(self.path)
self.restartApplication.emit()
self.restart_on_save = False
self.close()
else:
return
self.restart_on_save = True
logging.debug(f"saving config file to: {self.path}")
logging.debug("saving config file to: %s", self.path)
self._save_to_path(self.path)
else:
self.statusbar.showMessage("No values changed")
Expand Down
4 changes: 2 additions & 2 deletions mslib/msui/mpl_qtwidget.py
Original file line number Diff line number Diff line change
Expand Up @@ -506,7 +506,7 @@ def draw_vertical_lines(self, highlight, lats, lons):
try:
self.ax.lines.remove(line)
except ValueError as e:
logging.debug(f"Vertical line was somehow already removed:\n{e}")
logging.debug("Vertical line was somehow already removed:\n%s", e)
self.vertical_lines.remove(line)

# Add vertical lines
Expand Down Expand Up @@ -655,7 +655,7 @@ def redraw_xaxis(self, lats, lons):
try:
self.ax.lines.remove(line)
except ValueError as e:
logging.debug(f"Vertical line was somehow already removed:\n{e}")
logging.debug("Vertical line was somehow already removed:\n%s", e)
self.vertical_lines = []

def draw_vertical_lines(self, highlight, lats, lons):
Expand Down
12 changes: 6 additions & 6 deletions mslib/msui/mscolab.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ def new_user_handler(self):
try:
error_msg = json.loads(r.text)["message"]
except Exception as e:
logging.debug(f"Unexpected error occured {e}")
logging.debug("Unexpected error occured %s", e)
error_msg = "Unexpected error occured. Please try again."
self.set_status("Error", error_msg)

Expand Down Expand Up @@ -392,7 +392,7 @@ def newuser_server_auth(self):
try:
error_msg = json.loads(r.text)["message"]
except Exception as e:
logging.debug(f"Unexpected error occured {e}")
logging.debug("Unexpected error occured %s", e)
error_msg = "Unexpected error occured. Please try again."
self.set_status("Error", error_msg)
elif r.status_code == 204:
Expand Down Expand Up @@ -525,11 +525,11 @@ def create_dir(self):
try:
_ = fs.open_fs(self.data_dir)
except fs.errors.CreateFailed:
logging.error(f'Make sure that the FS url "{self.data_dir}" exists')
logging.error('Make sure that the FS url "%s" exists', self.data_dir)
show_popup(self.ui, "Error", f'FS Url: "{self.data_dir}" does not exist!')
sys.exit()
except fs.opener.errors.UnsupportedProtocol:
logging.error(f'FS url "{self.data_dir}" not supported')
logging.error('FS url "%s" not supported', self.data_dir)
show_popup(self.ui, "Error", f'FS Url: "{self.data_dir}" not supported!')
sys.exit()
else:
Expand Down Expand Up @@ -573,7 +573,7 @@ def after_login(self, emailid, url, r):
try:
self.conn = sc.ConnectionManager(self.token, user=self.user, mscolab_server_url=self.mscolab_server_url)
except Exception as ex:
logging.debug(f"Couldn't create a socket connection: {ex}")
logging.debug("Couldn't create a socket connection: %s", ex)
show_popup(self.ui, "Error", "Couldn't create a socket connection. Maybe the mscolab server is too old."
"New Login required!")
self.logout()
Expand Down Expand Up @@ -1384,7 +1384,7 @@ def delete_operation_from_list(self, op_id):
remove_item = item
break
if remove_item is not None:
logging.debug(f"remove_item: {remove_item}")
logging.debug("remove_item: %s", remove_item)
self.ui.listOperationsMSC.takeItem(self.ui.listOperationsMSC.row(remove_item))
return remove_item.operation_path

Expand Down
4 changes: 2 additions & 2 deletions mslib/msui/multilayers.py
Original file line number Diff line number Diff line change
Expand Up @@ -619,7 +619,7 @@ def _parse_itimes(self):
self.allowed_init_times = sorted(self.parent.dock_widget.parse_time_extent(values))
self.itimes = [_time.isoformat() + "Z" for _time in self.allowed_init_times]
if len(self.allowed_init_times) == 0:
logging.error(f"Cannot determine init time format of {self.header.text(0)} for {self.text(0)}")
logging.error("Cannot determine init time format of %s for %s", self.header.text(0), self.text(0))
self.is_invalid = True
else:
self.itime = self.itimes[-1]
Expand All @@ -638,7 +638,7 @@ def _parse_vtimes(self):
self.allowed_valid_times = sorted(self.parent.dock_widget.parse_time_extent(values))
self.vtimes = [_time.isoformat() + "Z" for _time in self.allowed_valid_times]
if len(self.allowed_valid_times) == 0:
logging.error(f"Cannot determine valid time format of {self.header.text(0)} for {self.text(0)}")
logging.error("Cannot determine valid time format of %s for %s", self.header.text(0), self.text(0))
self.is_invalid = True
else:
if self.itime:
Expand Down
4 changes: 2 additions & 2 deletions mslib/mswms/gallery_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
else:
STATIC_LOCATION = os.path.join(os.path.dirname(os.path.abspath(mswms_settings.__file__)), "gallery")
except ImportError as e:
logging.warning(f"{e}. Can't generate gallery.")
logging.warning("%s. Can't generate gallery.", e)

DOCS_LOCATION = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "docs", "gallery")

Expand Down Expand Up @@ -457,7 +457,7 @@ def write_html(path, sphinx=False, plot_types=None):

with open(os.path.join(path, "plots.html"), "w+") as file:
file.write(html + end)
logging.info(f"plots.html created at {os.path.join(path, 'plots.html')}")
logging.info("plots.html created at %s", os.path.join(path, 'plots.html'))


def import_instructions(plot_object, l_type, layer, native_import=None, dataset=""):
Expand Down
18 changes: 10 additions & 8 deletions mslib/mswms/wms.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,9 +283,10 @@ def generate_gallery(self, create=False, clear=False, generate_code=False, sphin

for itime in sorted(init_times):
if itime and plot_driver.get_init_times() and itime not in plot_driver.get_init_times():
logging.warning(f"Requested itime {itime} not present for "
f"{dataset} {plot_object.name}! itimes present: "
f"{plot_driver.get_init_times()}")
logging.warning("Requested itime %s not present for "
"%s %s! itimes present: "
"%s", itime, dataset, plot_object.name, plot_driver.get_init_times()
)
continue
elif not plot_driver.get_init_times():
itime = None
Expand All @@ -309,8 +310,9 @@ def generate_gallery(self, create=False, clear=False, generate_code=False, sphin

for vtime in sorted(valid_times):
if vtime and i_vtimes and vtime not in i_vtimes:
logging.warning(f"Requested vtime {vtime} at {itime} not present for "
f"{dataset} {plot_object.name}! vtimes present: {i_vtimes}")
logging.warning("Requested vtime %s at %s not present for "
"%s %s! vtimes present: %s", vtime, itime, dataset,
plot_object.name, i_vtimes)
continue
elif not i_vtimes:
vtime = None
Expand Down Expand Up @@ -372,9 +374,9 @@ def generate_gallery(self, create=False, clear=False, generate_code=False, sphin
for level in sorted(rendered_levels):
if level and elevations and level \
not in [float(elev) for elev in elevations]:
logging.warning(f"Requested level {level} not present for "
f"{dataset} {plot_object.name}! Levels present: "
f"{elevations}")
logging.warning("Requested level %s not present for "
"%s %s! Levels present: "
"%s", level, dataset, plot_object.name, elevations)
continue
elif not elevations:
level = None
Expand Down
4 changes: 2 additions & 2 deletions mslib/utils/airdata.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,13 @@
]


def download_progress(file_path, url, progress_callback=lambda f: logging.info(f"{int(f)}KB Downloaded")):
def download_progress(file_path, url, progress_callback=lambda f: logging.info("%sKB Downloaded", int(f))):
"""
Downloads the file at the given url to file_path and keeps track of the progress
"""
try:
with open(file_path, "wb+") as file:
logging.info(f"Downloading to {file_path}. This might take a while.")
logging.info("Downloading to %s. This might take a while.", file_path)
response = requests.get(url, stream=True, timeout=5)
length = response.headers.get("content-length")
if length is None: # no content length header
Expand Down
8 changes: 4 additions & 4 deletions mslib/utils/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -376,11 +376,11 @@ def read_config_file(path=constants.MSUI_SETTINGS):
try:
json_file_data = json.loads(file_content, object_pairs_hook=dict_raise_on_duplicates_empty)
except json.JSONDecodeError as e:
logging.error(f"Error while loading json file {e}")
logging.error("Error while loading json file %s", e)
error_message = f"Unexpected error while loading config\n{e}"
raise FatalUserError(error_message)
except ValueError as e:
logging.error(f"Error while loading json file {e}")
logging.error("Error while loading json file %s", e)
error_message = f"Invalid keys detected in config\n{e}"
raise FatalUserError(error_message)
else:
Expand Down Expand Up @@ -424,11 +424,11 @@ def modify_config_file(data, path=constants.MSUI_SETTINGS):
_fs.writetext(file_name, json.dumps(modified_data, indent=4))
read_config_file()
except json.JSONDecodeError as e:
logging.error(f"Error while loading json file {e}")
logging.error("Error while loading json file %s", e)
error_message = f"Unexpected error while loading config\n{e}"
raise FatalUserError(error_message)
except ValueError as e:
logging.error(f"Error while loading json file {e}")
logging.error("Error while loading json file %s", e)
error_message = f"Invalid keys detected in config\n{e}"
raise FatalUserError(error_message)
else:
Expand Down

0 comments on commit 7ff05ed

Please sign in to comment.