Пример #1
0
    async def test_rollover_happens_before_a_logline_is_emitted(self):
        handler = AsyncTimedRotatingFileHandler(
            filename=self.temp_file.name,
            when=RolloverInterval.SECONDS,
            backup_count=1,
        )
        formatter = Formatter("%(asctime)s %(message)s")
        handler.formatter = formatter

        self.assertTrue(os.path.exists(self.temp_file.name))

        await asyncio.sleep(1.1)

        record = make_log_record(msg="testing - initial")
        await handler.emit(record)
        await handler.close()
Пример #2
0
def setup_custom_logger():
    LOG_PATH = 'log'
    FileUtils.create_folder_if_not_exists(LOG_PATH)

    handler = AsyncTimedRotatingFileHandler(
        filename="log/think.log",
        when=RolloverInterval.HOURS,
        backup_count=48,
    )
    formatter = logging.Formatter(
        "[%(asctime)s] %(threadName)s - %(pathname)s %(funcName)s():%(lineno)d  %(levelname)s %(message)s"
    )
    handler.formatter = formatter

    logger = Logger.with_default_handlers(formatter=formatter)
    logger.addHandler(handler)
    logger.setLevel(logging.DEBUG)

    return logger
Пример #3
0
    async def test_rollover(self):
        handler = AsyncTimedRotatingFileHandler(
            filename=self.temp_file.name,
            when=RolloverInterval.SECONDS,
            backup_count=1,
        )
        formatter = logging.Formatter("%(asctime)s %(message)s")
        handler.formatter = formatter
        r1 = logging.makeLogRecord({"msg": "testing - initial"})
        await handler.emit(r1)
        self.assertTrue(os.path.exists(self.temp_file.name))

        await asyncio.sleep(1.1)

        r2 = logging.makeLogRecord({"msg": "testing - after delay"})
        await handler.emit(r2)
        await handler.close()
        # At this point, we should have a recent rotated file which we
        # can test for the existence of. However, in practice, on some
        # machines which run really slowly, we don't know how far back
        # in time to go to look for the log file. So, we go back a fair
        # bit, and stop as soon as we see a rotated file. In theory this
        # could of course still fail, but the chances are lower.
        found = False
        now = datetime.datetime.now()
        GO_BACK = 5 * 60  # seconds
        for secs in range(GO_BACK):
            prev = now - datetime.timedelta(seconds=secs)
            fn = self.temp_file.name + prev.strftime(".%Y-%m-%d_%H-%M-%S")
            found = os.path.exists(fn)
            if found:
                self.files_to_remove.append(fn)
                break

        self.assertTrue(
            found, msg=f"No rotated files found, went back {GO_BACK} seconds"
        )