Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DM-33950: Ensure that periodic logger reports the caller filename #118

Merged
merged 1 commit into from
Mar 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 6 additions & 1 deletion python/lsst/utils/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,11 @@ def __init__(self, logger: LsstLoggers, interval: Optional[float] = None, level:
self.next_log_time = time.time() + self.interval
self.num_issued = 0

# The stacklevel we need to issue logs is determined by the type
# of logger we have been given. A LoggerAdapter has an extra
# level of indirection.
self._stacklevel = 3 if isinstance(self.logger, LoggerAdapter) else 2
timj marked this conversation as resolved.
Show resolved Hide resolved

def log(self, msg: str, *args: Any) -> bool:
"""Issue a log message if the interval has elapsed.

Expand All @@ -382,7 +387,7 @@ def log(self, msg: str, *args: Any) -> bool:
issued by the logging system.
"""
if (current_time := time.time()) > self.next_log_time:
self.logger.log(self.level, msg, *args)
self.logger.log(self.level, msg, *args, stacklevel=self._stacklevel)
self.next_log_time = current_time + self.interval
self.num_issued += 1
return True
Expand Down
8 changes: 8 additions & 0 deletions tests/test_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ def test_periodic(self):
self.assertEqual(periodic.num_issued, 2)
self.assertEqual(cm.output[0], f"VERBOSE:{logger.name}:Message")
self.assertEqual(cm.output[1], f"VERBOSE:{logger.name}:Message 1")
self.assertEqual(cm.records[0].filename, "test_logging.py", str(cm.records[0]))

# Create a new periodic logger with small delay.
# One message should be issued.
Expand All @@ -120,6 +121,13 @@ def test_periodic(self):
self.assertEqual(periodic.num_issued, 1)
self.assertEqual(cm.output[0], f"INFO:{logger.name}:Message 1")

# Again with a standard python Logger.
pylog = logging.getLogger("python.logger")
periodic = PeriodicLogger(pylog, interval=0.0, level=logging.DEBUG)
with self.assertLogs(pylog.name, level=logging.DEBUG) as cm:
periodic.log("Message")
self.assertEqual(cm.records[0].filename, "test_logging.py", str(cm.records[0]))


if __name__ == "__main__":
unittest.main()