diff --git a/src/sdsstools/logger.py b/src/sdsstools/logger.py index 6a026e2..b4d7341 100644 --- a/src/sdsstools/logger.py +++ b/src/sdsstools/logger.py @@ -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. @@ -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)) @@ -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), diff --git a/test/test_logger.py b/test/test_logger.py index 687a861..29e3b9b 100644 --- a/test/test_logger.py +++ b/test/test_logger.py @@ -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)