logger: use lazy formatting

Fixes #1843
This commit is contained in:
Alex Hall
2022-07-05 02:09:25 +03:00
committed by Ruslan Kuprieiev
parent cacc2f14cb
commit 03b789e206
21 changed files with 61 additions and 54 deletions
+2 -2
View File
@@ -50,7 +50,7 @@ def is_enabled():
Config(validate=False).get("core", {}).get("analytics", "true")
)
logger.debug("Analytics is {}abled.".format("en" if enabled else "dis"))
logger.debug("Analytics is %sabled.", "en" if enabled else "dis")
return enabled
@@ -187,4 +187,4 @@ def _find_or_create_user_id():
return user_id
except LockError:
logger.debug(f"Failed to acquire '{lockfile}'")
logger.debug("Failed to acquire %r", lockfile)
+1 -1
View File
@@ -16,7 +16,7 @@ class CmdFreezeBase(CmdBase):
try:
func(target)
except DvcException:
logger.exception(f"failed to {name} '{target}'")
logger.exception("failed to %s %r", name, target)
ret = 1
return ret
+1 -1
View File
@@ -18,7 +18,7 @@ class CmdGetUrl(CmdBaseNoRepo):
Repo.get_url(self.args.url, out=self.args.out, jobs=self.args.jobs)
return 0
except DvcException:
logger.exception(f"failed to get '{self.args.url}'")
logger.exception("failed to get %r", self.args.url)
return 1
+1 -1
View File
@@ -42,7 +42,7 @@ class CmdList(CmdBaseNoRepo):
ui.write("\n".join(entries))
return 0
except DvcException:
logger.exception(f"failed to list '{self.args.url}'")
logger.exception("failed to list %r", self.args.url)
return 1
+1 -1
View File
@@ -187,7 +187,7 @@ class Config(dict):
filename = self.files[level]
fs = self._get_fs(level)
logger.debug(f"Writing '{filename}'.")
logger.debug("Writing %r.", filename)
fs.makedirs(os.path.dirname(filename))
+2 -2
View File
@@ -81,7 +81,7 @@ def _spawn_posix(cmd, env):
def _spawn(cmd, env):
logger.debug(f"Trying to spawn '{cmd}'")
logger.debug("Trying to spawn %r", cmd)
if os.name == "nt":
_spawn_windows(cmd, env)
@@ -90,7 +90,7 @@ def _spawn(cmd, env):
else:
raise NotImplementedError
logger.debug(f"Spawned '{cmd}'")
logger.debug("Spawned %r", cmd)
def daemon(args):
+1 -1
View File
@@ -64,7 +64,7 @@ class DataCloud:
return get_odb(cls(**config), fs_path, **config)
def _log_missing(self, status: "CompareStatusResult"):
if status.missing:
if status.missing and logger.isEnabledFor(logging.WARNING):
missing_desc = "\n".join(
f"name: {hash_info.obj_name}, {hash_info}"
for hash_info in status.missing
+1 -1
View File
@@ -197,7 +197,7 @@ class SingleStageFile(FileMixin):
assert not isinstance(stage, PipelineStage)
if self.verify:
check_dvcfile_path(self.repo, self.path)
logger.debug(f"Saving information to '{relpath(self.path)}'.")
logger.debug("Saving information to %r.", relpath(self.path))
dump_yaml(self.path, serialize.to_single_stage_file(stage))
self.repo.scm_context.track_file(self.relpath)
+2 -2
View File
@@ -541,7 +541,7 @@ class Output:
raise self.IsNotFileOrDirError(self)
if self.is_empty:
logger.warning(f"'{self}' is empty.")
logger.warning("'%s' is empty.", self)
self.ignore()
@@ -912,7 +912,7 @@ class Output:
except RemoteMissingDepsError: # pylint: disable=try-except-raise
raise
except DvcException:
logger.debug(f"failed to pull cache for '{self}'")
logger.debug("failed to pull cache for '%s'", self)
try:
ocheck(self.odb, self.odb.get(self.hash_info.value))
+1 -1
View File
@@ -52,5 +52,5 @@ def password(statement):
Returns:
str: password entered by the user.
"""
logger.info(f"{statement}: ")
logger.info("%s: ", statement)
return getpass("")
+6 -3
View File
@@ -348,10 +348,11 @@ class BaseExecutor(ABC):
if git_remote == dvc.root_dir:
logger.warning(
f"'{git_remote}' points to the current Git repo, experiment "
"%r points to the current Git repo, experiment "
"Git refs will not be pushed. But DVC cache and run cache "
"will automatically be pushed to the default DVC remote "
"(if any) on each experiment commit."
"(if any) on each experiment commit.",
git_remote,
)
try:
dvc.scm.validate_git_remote(git_remote)
@@ -603,7 +604,9 @@ class BaseExecutor(ABC):
except BaseException as exc: # pylint: disable=broad-except
logger.warning(
"Something went wrong while auto pushing experiment "
f"to the remote '{git_remote}': {exc}"
"to the remote %r: %s",
git_remote,
exc,
)
@classmethod
+2 -2
View File
@@ -82,7 +82,7 @@ def _pull(
force: bool,
) -> Mapping[SyncStatus, List["ExpRefInfo"]]:
refspec_list = [f"{exp_ref}:{exp_ref}" for exp_ref in refs]
logger.debug(f"git pull experiment '{git_remote}' -> '{refspec_list}'")
logger.debug("git pull experiment %r -> '%s'", git_remote, refspec_list)
with TqdmGit(desc="Fetching git refs") as pbar:
results: Mapping[str, SyncStatus] = repo.scm.fetch_refspecs(
@@ -113,7 +113,7 @@ def _pull_cache(
if isinstance(refs, ExpRefInfo):
refs = [refs]
revs = list(exp_commits(repo.scm, refs))
logger.debug(f"dvc fetch experiment '{refs}'")
logger.debug("dvc fetch experiment '%s'", refs)
repo.fetch(
jobs=jobs, remote=dvc_remote, run_cache=run_cache, revs=revs, odb=odb
)
+2 -2
View File
@@ -85,7 +85,7 @@ def _push(
from ...scm import GitAuthError
refspec_list = [f"{exp_ref}:{exp_ref}" for exp_ref in refs]
logger.debug(f"git push experiment '{refs}' -> '{git_remote}'")
logger.debug("git push experiment %r -> '%s'", refspec_list, git_remote)
with TqdmGit(desc="Pushing git refs") as pbar:
try:
@@ -118,5 +118,5 @@ def _push_cache(
if isinstance(refs, ExpRefInfo):
refs = [refs]
revs = list(exp_commits(repo.scm, refs))
logger.debug(f"dvc push experiment '{refs}'")
logger.debug("dvc push experiment '%s'", refs)
repo.push(jobs=jobs, remote=dvc_remote, run_cache=run_cache, revs=revs)
+1 -1
View File
@@ -76,7 +76,7 @@ def gc(
removed = ogc(odb, used_obj_ids, jobs=jobs)
if not removed:
logger.info(f"No unused '{scheme}' cache to remove.")
logger.info("No unused %r cache to remove.", scheme)
if not cloud:
return
+3 -2
View File
@@ -33,8 +33,9 @@ def _reproduce_stage(stage: "Stage", **kwargs):
if stage.frozen and not stage.is_import:
logger.warning(
"{} is frozen. Its dependencies are"
" not going to be reproduced.".format(stage)
"%s is frozen. Its dependencies are"
" not going to be reproduced.",
stage,
)
stage = stage.reproduce(**kwargs)
+5 -1
View File
@@ -124,7 +124,11 @@ class SCMContext:
if autostage:
self.track_changed_files()
elif not quiet and not isinstance(self.scm, NoSCM):
elif (
not quiet
and not isinstance(self.scm, NoSCM)
and logger.isEnabledFor(logging.INFO)
):
add_cmd = self._make_git_add_cmd(self.files_to_track)
logger.info(
f"\nTo track the changes with git, run:\n" f"\n{add_cmd}"
+3 -2
View File
@@ -16,8 +16,9 @@ def _joint_status(pairs):
for stage, filter_info in pairs:
if stage.frozen and not stage.is_repo_import:
logger.warning(
"{} is frozen. Its dependencies are"
" not going to be shown in the status output.".format(stage)
"%s is frozen. Its dependencies are"
" not going to be shown in the status output.",
stage,
)
status_info.update(
stage.status(check_updates=True, filter_info=filter_info)
+11 -11
View File
@@ -323,10 +323,10 @@ class Stage(params.StageParams):
status = dep.status()
if status:
logger.debug(
"Dependency '{dep}' of {stage} changed because it is "
"'{status}'.".format(
dep=dep, stage=self, status=status[str(dep)]
)
"Dependency '%s' of %s changed because it is %r.",
dep,
self,
status[str(dep)],
)
return True
return False
@@ -337,10 +337,10 @@ class Stage(params.StageParams):
status = out.status()
if status:
logger.debug(
"Output '{out}' of {stage} changed because it is "
"'{status}'".format(
out=out, stage=self, status=status[str(out)]
)
"Output '%s' of %s changed because it is %r.",
out,
self,
status[str(out)],
)
return True
@@ -373,7 +373,7 @@ class Stage(params.StageParams):
out.unprotect()
continue
logger.debug(f"Removing output '{out}' of {self}.")
logger.debug("Removing output '%s' of %s.", out, self)
out.remove(ignore_remove=ignore_remove)
def unprotect_outs(self):
@@ -429,7 +429,7 @@ class Stage(params.StageParams):
self.run(**kwargs)
logger.debug(f"{self} was reproduced")
logger.debug("%s was reproduced", self)
return self
@@ -452,7 +452,7 @@ class Stage(params.StageParams):
m = None
else:
m = compute_md5(self)
logger.debug(f"Computed {self} md5: '{m}'")
logger.debug("Computed %s md5: %r", self, m)
return m
def save(self, allow_missing=False):
+1 -5
View File
@@ -32,11 +32,7 @@ def update_import(stage, rev=None, to_remote=False, remote=None, jobs=None):
def sync_import(stage, dry=False, force=False, jobs=None):
"""Synchronize import's outs to the workspace."""
logger.info(
"Importing '{dep}' -> '{out}'".format(
dep=stage.deps[0], out=stage.outs[0]
)
)
logger.info("Importing '%s' -> '%s'", stage.deps[0], stage.outs[0])
if dry:
return
+3 -4
View File
@@ -62,9 +62,8 @@ def find_pager():
if os.system(f"({DEFAULT_PAGER}) 2>{os.devnull}") != 0:
logger.warning(
"Unable to find `less` in the PATH. Check out "
"{} for more info.".format(
format_link("https://man.dvc.org/pipeline/show")
)
"%s for more info.",
format_link("https://man.dvc.org/pipeline/show"),
)
else:
pager = DEFAULT_PAGER
@@ -86,7 +85,7 @@ def find_pager():
def pager(text: str) -> None:
_pager = find_pager()
logger.trace(f"Using pager: '{_pager}'") # type: ignore[attr-defined]
logger.trace("Using pager: %r", _pager) # type: ignore[attr-defined]
make_pager(_pager)(text)
+11 -8
View File
@@ -37,7 +37,7 @@ class Updater:
ctime = os.path.getmtime(self.updater_file)
outdated = time.time() - ctime >= self.TIMEOUT
if outdated:
logger.debug(f"'{self.updater_file}' is outdated")
logger.debug("%r is outdated", self.updater_file)
return outdated
def _with_lock(self, func, action):
@@ -47,8 +47,11 @@ class Updater:
with self.lock:
func()
except LockError:
msg = "Failed to acquire '{}' before {} updates"
logger.debug(msg.format(self.lock.lockfile, action))
logger.debug(
"Failed to acquire %r before %s updates",
self.lock.lockfile,
action,
)
def check(self):
from dvc.utils import env2bool
@@ -75,8 +78,9 @@ class Updater:
info = json.load(fobj)
latest = info["version"]
except Exception as exc: # pylint: disable=broad-except
msg = "'{}' is not a valid json: {}"
logger.debug(msg.format(self.updater_file, exc))
logger.debug(
"%r is not a valid json: %s", self.updater_file, exc
)
self.fetch()
return
@@ -101,8 +105,7 @@ class Updater:
resp = requests.get(self.URL, timeout=self.TIMEOUT_GET)
info = resp.json()
except requests.exceptions.RequestException as exc:
msg = "Failed to retrieve latest version: {}"
logger.debug(msg.format(exc))
logger.debug("Failed to retrieve latest version: %s", exc)
return
with open(self.updater_file, "w+", encoding="utf-8") as fobj:
@@ -171,7 +174,7 @@ class Updater:
Config(validate=False).get("core", {}).get("check_update", "true")
)
logger.debug(
"Check for update is {}abled.".format("en" if enabled else "dis")
"Check for update is %sabled.", "en" if enabled else "dis"
)
return enabled