Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 10cdd03

Browse files
authoredJan 26, 2024
Merge pull request #1813 from EliahKagan/logging
Don't suppress messages when logging is not configured
2 parents 9a7cec1 + bc42ee5 commit 10cdd03

File tree

11 files changed

+57
-68
lines changed

11 files changed

+57
-68
lines changed
 

‎git/cmd.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -81,8 +81,7 @@
8181
"strip_newline_in_stdout",
8282
}
8383

84-
log = logging.getLogger(__name__)
85-
log.addHandler(logging.NullHandler())
84+
_logger = logging.getLogger(__name__)
8685

8786
__all__ = ("Git",)
8887

@@ -146,7 +145,7 @@ def pump_stream(
146145
handler(line)
147146

148147
except Exception as ex:
149-
log.error(f"Pumping {name!r} of cmd({remove_password_if_present(cmdline)}) failed due to: {ex!r}")
148+
_logger.error(f"Pumping {name!r} of cmd({remove_password_if_present(cmdline)}) failed due to: {ex!r}")
150149
if "I/O operation on closed file" not in str(ex):
151150
# Only reraise if the error was not due to the stream closing
152151
raise CommandError([f"<{name}-pump>"] + remove_password_if_present(cmdline), ex) from ex
@@ -600,7 +599,7 @@ def _terminate(self) -> None:
600599
self.status = self._status_code_if_terminate or proc.poll()
601600
return
602601
except OSError as ex:
603-
log.info("Ignored error after process had died: %r", ex)
602+
_logger.info("Ignored error after process had died: %r", ex)
604603

605604
# It can be that nothing really exists anymore...
606605
if os is None or getattr(os, "kill", None) is None:
@@ -613,7 +612,7 @@ def _terminate(self) -> None:
613612

614613
self.status = self._status_code_if_terminate or status
615614
except OSError as ex:
616-
log.info("Ignored error after process had died: %r", ex)
615+
_logger.info("Ignored error after process had died: %r", ex)
617616
# END exception handling
618617

619618
def __del__(self) -> None:
@@ -654,7 +653,7 @@ def read_all_from_possibly_closed_stream(stream: Union[IO[bytes], None]) -> byte
654653

655654
if status != 0:
656655
errstr = read_all_from_possibly_closed_stream(p_stderr)
657-
log.debug("AutoInterrupt wait stderr: %r" % (errstr,))
656+
_logger.debug("AutoInterrupt wait stderr: %r" % (errstr,))
658657
raise GitCommandError(remove_password_if_present(self.args), status, errstr)
659658
return status
660659

@@ -1018,7 +1017,7 @@ def execute(
10181017
# Remove password for the command if present.
10191018
redacted_command = remove_password_if_present(command)
10201019
if self.GIT_PYTHON_TRACE and (self.GIT_PYTHON_TRACE != "full" or as_process):
1021-
log.info(" ".join(redacted_command))
1020+
_logger.info(" ".join(redacted_command))
10221021

10231022
# Allow the user to have the command executed in their working dir.
10241023
try:
@@ -1055,7 +1054,7 @@ def execute(
10551054
stdout_sink = PIPE if with_stdout else getattr(subprocess, "DEVNULL", None) or open(os.devnull, "wb")
10561055
if shell is None:
10571056
shell = self.USE_SHELL
1058-
log.debug(
1057+
_logger.debug(
10591058
"Popen(%s, cwd=%s, stdin=%s, shell=%s, universal_newlines=%s)",
10601059
redacted_command,
10611060
cwd,
@@ -1167,17 +1166,17 @@ def as_text(stdout_value: Union[bytes, str]) -> str:
11671166
# END as_text
11681167

11691168
if stderr_value:
1170-
log.info(
1169+
_logger.info(
11711170
"%s -> %d; stdout: '%s'; stderr: '%s'",
11721171
cmdstr,
11731172
status,
11741173
as_text(stdout_value),
11751174
safe_decode(stderr_value),
11761175
)
11771176
elif stdout_value:
1178-
log.info("%s -> %d; stdout: '%s'", cmdstr, status, as_text(stdout_value))
1177+
_logger.info("%s -> %d; stdout: '%s'", cmdstr, status, as_text(stdout_value))
11791178
else:
1180-
log.info("%s -> %d", cmdstr, status)
1179+
_logger.info("%s -> %d", cmdstr, status)
11811180
# END handle debug printing
11821181

11831182
if with_exceptions and status != 0:

‎git/config.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -60,10 +60,7 @@
6060

6161
__all__ = ("GitConfigParser", "SectionConstraint")
6262

63-
64-
log = logging.getLogger("git.config")
65-
log.addHandler(logging.NullHandler())
66-
63+
_logger = logging.getLogger(__name__)
6764

6865
CONFIG_LEVELS: ConfigLevels_Tup = ("system", "user", "global", "repository")
6966
"""The configuration level of a configuration file."""
@@ -412,7 +409,7 @@ def release(self) -> None:
412409
try:
413410
self.write()
414411
except IOError:
415-
log.error("Exception during destruction of GitConfigParser", exc_info=True)
412+
_logger.error("Exception during destruction of GitConfigParser", exc_info=True)
416413
except ReferenceError:
417414
# This happens in Python 3... and usually means that some state cannot be
418415
# written as the sections dict cannot be iterated. This usually happens when
@@ -712,7 +709,7 @@ def write(self) -> None:
712709
# END assert multiple files
713710

714711
if self._has_includes():
715-
log.debug(
712+
_logger.debug(
716713
"Skipping write-back of configuration file as include files were merged in."
717714
+ "Set merge_includes=False to prevent this."
718715
)

‎git/objects/commit.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,7 @@
5252

5353
# ------------------------------------------------------------------------
5454

55-
log = logging.getLogger("git.objects.commit")
56-
log.addHandler(logging.NullHandler())
55+
_logger = logging.getLogger(__name__)
5756

5857
__all__ = ("Commit",)
5958

@@ -767,7 +766,7 @@ def _deserialize(self, stream: BytesIO) -> "Commit":
767766
self.author_tz_offset,
768767
) = parse_actor_and_date(author_line.decode(self.encoding, "replace"))
769768
except UnicodeDecodeError:
770-
log.error(
769+
_logger.error(
771770
"Failed to decode author line '%s' using encoding %s",
772771
author_line,
773772
self.encoding,
@@ -781,7 +780,7 @@ def _deserialize(self, stream: BytesIO) -> "Commit":
781780
self.committer_tz_offset,
782781
) = parse_actor_and_date(committer_line.decode(self.encoding, "replace"))
783782
except UnicodeDecodeError:
784-
log.error(
783+
_logger.error(
785784
"Failed to decode committer line '%s' using encoding %s",
786785
committer_line,
787786
self.encoding,
@@ -795,7 +794,7 @@ def _deserialize(self, stream: BytesIO) -> "Commit":
795794
try:
796795
self.message = self.message.decode(self.encoding, "replace")
797796
except UnicodeDecodeError:
798-
log.error(
797+
_logger.error(
799798
"Failed to decode message '%s' using encoding %s",
800799
self.message,
801800
self.encoding,

‎git/objects/submodule/base.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040

4141

4242
# typing ----------------------------------------------------------------------
43+
4344
from typing import Callable, Dict, Mapping, Sequence, TYPE_CHECKING, cast
4445
from typing import Any, Iterator, Union
4546

@@ -50,14 +51,11 @@
5051
from git.repo import Repo
5152
from git.refs import Head
5253

53-
5454
# -----------------------------------------------------------------------------
5555

5656
__all__ = ["Submodule", "UpdateProgress"]
5757

58-
59-
log = logging.getLogger("git.objects.submodule.base")
60-
log.addHandler(logging.NullHandler())
58+
_logger = logging.getLogger(__name__)
6159

6260

6361
class UpdateProgress(RemoteProgress):
@@ -731,7 +729,7 @@ def update(
731729
)
732730
mrepo.head.reference.set_tracking_branch(remote_branch)
733731
except (IndexError, InvalidGitRepositoryError):
734-
log.warning("Failed to checkout tracking branch %s", self.branch_path)
732+
_logger.warning("Failed to checkout tracking branch %s", self.branch_path)
735733
# END handle tracking branch
736734

737735
# NOTE: Have to write the repo config file as well, otherwise the
@@ -761,14 +759,14 @@ def update(
761759
binsha = rcommit.binsha
762760
hexsha = rcommit.hexsha
763761
else:
764-
log.error(
762+
_logger.error(
765763
"%s a tracking branch was not set for local branch '%s'",
766764
msg_base,
767765
mrepo.head.reference,
768766
)
769767
# END handle remote ref
770768
else:
771-
log.error("%s there was no local tracking branch", msg_base)
769+
_logger.error("%s there was no local tracking branch", msg_base)
772770
# END handle detached head
773771
# END handle to_latest_revision option
774772

@@ -786,15 +784,15 @@ def update(
786784
if force:
787785
msg = "Will force checkout or reset on local branch that is possibly in the future of"
788786
msg += " the commit it will be checked out to, effectively 'forgetting' new commits"
789-
log.debug(msg)
787+
_logger.debug(msg)
790788
else:
791789
msg = "Skipping %s on branch '%s' of submodule repo '%s' as it contains un-pushed commits"
792790
msg %= (
793791
is_detached and "checkout" or "reset",
794792
mrepo.head,
795793
mrepo,
796794
)
797-
log.info(msg)
795+
_logger.info(msg)
798796
may_reset = False
799797
# END handle force
800798
# END handle if we are in the future
@@ -834,7 +832,7 @@ def update(
834832
except Exception as err:
835833
if not keep_going:
836834
raise
837-
log.error(str(err))
835+
_logger.error(str(err))
838836
# END handle keep_going
839837

840838
# HANDLE RECURSION

‎git/objects/submodule/root.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,7 @@
2222

2323
__all__ = ["RootModule", "RootUpdateProgress"]
2424

25-
log = logging.getLogger("git.objects.submodule.root")
26-
log.addHandler(logging.NullHandler())
25+
_logger = logging.getLogger(__name__)
2726

2827

2928
class RootUpdateProgress(UpdateProgress):
@@ -321,7 +320,7 @@ def update(
321320
# this way, it will be checked out in the next step.
322321
# This will change the submodule relative to us, so
323322
# the user will be able to commit the change easily.
324-
log.warning(
323+
_logger.warning(
325324
"Current sha %s was not contained in the tracking\
326325
branch at the new remote, setting it the the remote's tracking branch",
327326
sm.hexsha,
@@ -393,7 +392,7 @@ def update(
393392
except Exception as err:
394393
if not keep_going:
395394
raise
396-
log.error(str(err))
395+
_logger.error(str(err))
397396
# END handle keep_going
398397

399398
# FINALLY UPDATE ALL ACTUAL SUBMODULES

‎git/remote.py

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,7 @@
5858

5959
# -------------------------------------------------------------
6060

61-
62-
log = logging.getLogger("git.remote")
63-
log.addHandler(logging.NullHandler())
64-
61+
_logger = logging.getLogger(__name__)
6562

6663
__all__ = ("RemoteProgress", "PushInfo", "FetchInfo", "Remote")
6764

@@ -846,7 +843,7 @@ def _get_fetch_info_from_stderr(
846843
stderr_text = progress.error_lines and "\n".join(progress.error_lines) or ""
847844
proc.wait(stderr=stderr_text)
848845
if stderr_text:
849-
log.warning("Error lines received while fetching: %s", stderr_text)
846+
_logger.warning("Error lines received while fetching: %s", stderr_text)
850847

851848
for line in progress.other_lines:
852849
line = force_text(line)
@@ -867,9 +864,9 @@ def _get_fetch_info_from_stderr(
867864
msg += "length of progress lines %i should be equal to lines in FETCH_HEAD file %i\n"
868865
msg += "Will ignore extra progress lines or fetch head lines."
869866
msg %= (l_fil, l_fhi)
870-
log.debug(msg)
871-
log.debug(b"info lines: " + str(fetch_info_lines).encode("UTF-8"))
872-
log.debug(b"head info: " + str(fetch_head_info).encode("UTF-8"))
867+
_logger.debug(msg)
868+
_logger.debug(b"info lines: " + str(fetch_info_lines).encode("UTF-8"))
869+
_logger.debug(b"head info: " + str(fetch_head_info).encode("UTF-8"))
873870
if l_fil < l_fhi:
874871
fetch_head_info = fetch_head_info[:l_fil]
875872
else:
@@ -881,8 +878,8 @@ def _get_fetch_info_from_stderr(
881878
try:
882879
output.append(FetchInfo._from_line(self.repo, err_line, fetch_line))
883880
except ValueError as exc:
884-
log.debug("Caught error while parsing line: %s", exc)
885-
log.warning("Git informed while fetching: %s", err_line.strip())
881+
_logger.debug("Caught error while parsing line: %s", exc)
882+
_logger.warning("Git informed while fetching: %s", err_line.strip())
886883
return output
887884

888885
def _get_push_info(
@@ -924,7 +921,7 @@ def stdout_handler(line: str) -> None:
924921
if not output:
925922
raise
926923
elif stderr_text:
927-
log.warning("Error lines received while fetching: %s", stderr_text)
924+
_logger.warning("Error lines received while fetching: %s", stderr_text)
928925
output.error = e
929926

930927
return output

‎git/repo/base.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@
8989

9090
# -----------------------------------------------------------
9191

92-
log = logging.getLogger(__name__)
92+
_logger = logging.getLogger(__name__)
9393

9494
__all__ = ("Repo",)
9595

@@ -772,7 +772,7 @@ def is_valid_object(self, sha: str, object_type: Union[str, None] = None) -> boo
772772
if object_info.type == object_type.encode():
773773
return True
774774
else:
775-
log.debug(
775+
_logger.debug(
776776
"Commit hash points to an object of type '%s'. Requested were objects of type '%s'",
777777
object_info.type.decode(),
778778
object_type,
@@ -781,7 +781,7 @@ def is_valid_object(self, sha: str, object_type: Union[str, None] = None) -> boo
781781
else:
782782
return True
783783
except BadObject:
784-
log.debug("Commit hash is invalid.")
784+
_logger.debug("Commit hash is invalid.")
785785
return False
786786

787787
def _get_daemon_export(self) -> bool:
@@ -1298,7 +1298,7 @@ def _clone(
12981298
cmdline = getattr(proc, "args", "")
12991299
cmdline = remove_password_if_present(cmdline)
13001300

1301-
log.debug("Cmd(%s)'s unused stdout: %s", cmdline, stdout)
1301+
_logger.debug("Cmd(%s)'s unused stdout: %s", cmdline, stdout)
13021302
finalize_process(proc, stderr=stderr)
13031303

13041304
# Our git command could have a different working dir than our actual

‎git/util.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@
104104
"HIDE_WINDOWS_KNOWN_ERRORS",
105105
]
106106

107-
log = logging.getLogger(__name__)
107+
_logger = logging.getLogger(__name__)
108108

109109

110110
def _read_win_env_flag(name: str, default: bool) -> bool:
@@ -124,7 +124,7 @@ def _read_win_env_flag(name: str, default: bool) -> bool:
124124
except KeyError:
125125
return default
126126

127-
log.warning(
127+
_logger.warning(
128128
"The %s environment variable is deprecated. Its effect has never been documented and changes without warning.",
129129
name,
130130
)
@@ -135,7 +135,7 @@ def _read_win_env_flag(name: str, default: bool) -> bool:
135135
return False
136136
if adjusted_value in {"1", "true", "yes"}:
137137
return True
138-
log.warning("%s has unrecognized value %r, treating as %r.", name, value, default)
138+
_logger.warning("%s has unrecognized value %r, treating as %r.", name, value, default)
139139
return default
140140

141141

@@ -466,7 +466,7 @@ def is_cygwin_git(git_executable: Union[None, PathLike]) -> bool:
466466
# retcode = process.poll()
467467
is_cygwin = "CYGWIN" in uname_out
468468
except Exception as ex:
469-
log.debug("Failed checking if running in CYGWIN due to: %r", ex)
469+
_logger.debug("Failed checking if running in CYGWIN due to: %r", ex)
470470
_is_cygwin_cache[git_executable] = is_cygwin
471471

472472
return is_cygwin

‎test/lib/helper.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@
4545
"GIT_DAEMON_PORT",
4646
)
4747

48-
log = logging.getLogger(__name__)
48+
_logger = logging.getLogger(__name__)
4949

5050
# { Routines
5151

@@ -96,7 +96,7 @@ def wrapper(self, *args, **kwargs):
9696
try:
9797
return func(self, path, *args, **kwargs)
9898
except Exception:
99-
log.info(
99+
_logger.info(
100100
"Test %s.%s failed, output is at %r\n",
101101
type(self).__name__,
102102
func.__name__,
@@ -147,7 +147,7 @@ def repo_creator(self):
147147
try:
148148
return func(self, rw_repo)
149149
except: # noqa: E722 B001
150-
log.info("Keeping repo after failure: %s", repo_dir)
150+
_logger.info("Keeping repo after failure: %s", repo_dir)
151151
repo_dir = None
152152
raise
153153
finally:
@@ -212,7 +212,7 @@ def git_daemon_launched(base_path, ip, port):
212212
and setting the environment variable GIT_PYTHON_TEST_GIT_DAEMON_PORT to <port>
213213
"""
214214
)
215-
log.warning(msg, ex, ip, port, base_path, base_path, exc_info=1)
215+
_logger.warning(msg, ex, ip, port, base_path, base_path, exc_info=1)
216216

217217
yield # OK, assume daemon started manually.
218218

@@ -221,11 +221,11 @@ def git_daemon_launched(base_path, ip, port):
221221
finally:
222222
if gd:
223223
try:
224-
log.debug("Killing git-daemon...")
224+
_logger.debug("Killing git-daemon...")
225225
gd.proc.kill()
226226
except Exception as ex:
227227
# Either it has died (and we're here), or it won't die, again here...
228-
log.debug("Hidden error while Killing git-daemon: %s", ex, exc_info=1)
228+
_logger.debug("Hidden error while Killing git-daemon: %s", ex, exc_info=1)
229229

230230

231231
def with_rw_and_rw_remote_repo(working_tree_ref):
@@ -307,7 +307,7 @@ def remote_repo_creator(self):
307307
try:
308308
return func(self, rw_repo, rw_daemon_repo)
309309
except: # noqa: E722 B001
310-
log.info(
310+
_logger.info(
311311
"Keeping repos after failure: \n rw_repo_dir: %s \n rw_daemon_repo_dir: %s",
312312
rw_repo_dir,
313313
rw_daemon_repo_dir,

‎test/test_git.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ def test_it_uses_shell_or_not_as_specified(self, case):
141141
def test_it_logs_if_it_uses_a_shell(self, case):
142142
"""``shell=`` in the log message agrees with what is passed to `Popen`."""
143143
value_in_call, value_from_class = case
144-
with self.assertLogs(cmd.log, level=logging.DEBUG) as log_watcher:
144+
with self.assertLogs(cmd.__name__, level=logging.DEBUG) as log_watcher:
145145
mock_safer_popen = self._do_shell_combo(value_in_call, value_from_class)
146146
self._assert_logged_for_popen(log_watcher, "shell", mock_safer_popen.call_args.kwargs["shell"])
147147

@@ -151,7 +151,7 @@ def test_it_logs_if_it_uses_a_shell(self, case):
151151
)
152152
def test_it_logs_istream_summary_for_stdin(self, case):
153153
expected_summary, istream_argument = case
154-
with self.assertLogs(cmd.log, level=logging.DEBUG) as log_watcher:
154+
with self.assertLogs(cmd.__name__, level=logging.DEBUG) as log_watcher:
155155
self.git.execute(["git", "version"], istream=istream_argument)
156156
self._assert_logged_for_popen(log_watcher, "stdin", expected_summary)
157157

‎test/test_index.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252

5353
HOOKS_SHEBANG = "#!/usr/bin/env sh\n"
5454

55-
log = logging.getLogger(__name__)
55+
_logger = logging.getLogger(__name__)
5656

5757

5858
def _get_windows_ansi_encoding():
@@ -144,13 +144,13 @@ def check(cls):
144144
if process.returncode == 1 and re.search(r"\bhttps://aka.ms/wslstore\b", text):
145145
return cls.WslNoDistro(process, text)
146146
if process.returncode != 0:
147-
log.error("Error running bash.exe to check WSL status: %s", text)
147+
_logger.error("Error running bash.exe to check WSL status: %s", text)
148148
return cls.CheckError(process, text)
149149
if text == "0":
150150
return cls.Wsl()
151151
if text == "1":
152152
return cls.Native()
153-
log.error("Strange output checking WSL status: %s", text)
153+
_logger.error("Strange output checking WSL status: %s", text)
154154
return cls.CheckError(process, text)
155155

156156
@staticmethod
@@ -174,7 +174,7 @@ def _decode(stdout):
174174
except UnicodeDecodeError:
175175
pass
176176
except LookupError as error:
177-
log.warning("%s", str(error)) # Message already says "Unknown encoding:".
177+
_logger.warning("%s", str(error)) # Message already says "Unknown encoding:".
178178

179179
# Assume UTF-8. If invalid, substitute Unicode replacement characters.
180180
return stdout.decode("utf-8", errors="replace")

0 commit comments

Comments
 (0)
Please sign in to comment.