Skip to content

Commit

Permalink
Adds options for the TimedRotatingFileHandler (#40)
Browse files Browse the repository at this point in the history
* adding options for timedfh

* linting

* adding test

* linting
  • Loading branch information
havok2063 authored Nov 9, 2023
1 parent 35300e3 commit df7283a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
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 @@ def start_file_logger(
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 @@ def start_file_logger(
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 @@ def start_file_logger(
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)

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

0 comments on commit df7283a

Please sign in to comment.