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

Adds options for the TimedRotatingFileHandler #40

Merged
merged 4 commits into from
Nov 9, 2023
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions src/sdsstools/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,9 @@
mode: str = "a",
rotating: bool = True,
rollover: bool = False,
when: str = "midnight",
utc: bool = True,
at_time: Union[str, datetime.time] = None,
):
"""Start file logging.

Expand All @@ -336,6 +339,14 @@
rollover
If `True` and ``rotating=True` and the log file already exists, does a
rollover before starting to log.
when
The type of time interval. Allowed values are those from
`TimedRotatingFileHandler`.
utc
If `True`, times in UTC will be used; otherwise local time is used.
at_time
The time of day when rollover occurs, when rollover is set to occur
at “midnight” or “on a particular weekday”.
"""

log_file_path = os.path.realpath(os.path.expanduser(path))
Expand All @@ -352,15 +363,19 @@
dst = str(log_file_path) + "." + now.strftime(SUFFIX)
shutil.move(str(log_file_path), dst)

# convert at_time to a datetime.time
if at_time and isinstance(at_time, str):
at_time = datetime.time.fromisoformat(at_time)

Check warning on line 368 in src/sdsstools/logger.py

View check run for this annotation

Codecov / codecov/patch

src/sdsstools/logger.py#L368

Added line #L368 was not covered by tests

if rotating:
self.fh = TimedRotatingFileHandler(
str(log_file_path), when="midnight", utc=True
str(log_file_path), when=when, utc=utc, atTime=at_time
)
self.fh.suffix = SUFFIX # type: ignore
else:
self.fh = logging.FileHandler(str(log_file_path), mode=mode)

except (IOError, OSError) as ee:
except (IOError, OSError, ValueError) as ee:
warnings.warn(
"log file {0!r} could not be opened for "
"writing: {1}".format(log_file_path, ee),
Expand Down
10 changes: 10 additions & 0 deletions test/test_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,16 @@ def test_logger_rotating_rollover(tmp_path):
assert len(list((tmp_path / "logs").glob("*"))) == 2


def test_logger_when_options(tmp_path):
log_file = tmp_path / "logs" / "test_log.log"

logger1 = get_logger(str(uuid.uuid4()))
logger1.start_file_logger(log_file, utc=False, when="M")

assert logger1.fh.when == "M"
assert logger1.fh.utc is False


def test_rich_handler_logger(caplog):
log = get_logger("test", use_rich_handler=True)

Expand Down