Example #1
0
def test_timed_rotating_file_handler(tmpdir, activation_strategy, backup_count):
    basename = str(tmpdir.join('trot.log'))
    handler = logbook.TimedRotatingFileHandler(
        basename, backup_count=backup_count)
    handler.format_string = '[{record.time:%H:%M}] {record.message}'

    def fake_record(message, year, month, day, hour=0,
                    minute=0, second=0):
        lr = logbook.LogRecord('Test Logger', logbook.WARNING,
                               message)
        lr.time = datetime(year, month, day, hour, minute, second)
        return lr

    with activation_strategy(handler):
        for x in xrange(10):
            handler.handle(fake_record('First One', 2010, 1, 5, x + 1))
        for x in xrange(20):
            handler.handle(fake_record('Second One', 2010, 1, 6, x + 1))
        for x in xrange(10):
            handler.handle(fake_record('Third One', 2010, 1, 7, x + 1))
        for x in xrange(20):
            handler.handle(fake_record('Last One', 2010, 1, 8, x + 1))

    files = sorted(x for x in os.listdir(str(tmpdir)) if x.startswith('trot'))

    assert files == ['trot-2010-01-0{0}.log'.format(i)
                     for i in xrange(5, 9)][-backup_count:]
    with open(str(tmpdir.join('trot-2010-01-08.log'))) as f:
        assert f.readline().rstrip() == '[01:00] Last One'
        assert f.readline().rstrip() == '[02:00] Last One'
    if backup_count > 1:
        with open(str(tmpdir.join('trot-2010-01-07.log'))) as f:
            assert f.readline().rstrip() == '[01:00] Third One'
            assert f.readline().rstrip() == '[02:00] Third One'
Example #2
0
def test_timed_rotating_file_handler__not_timed_filename_for_current(
        tmpdir, activation_strategy, backup_count, preexisting_file
):
    basename = str(tmpdir.join('trot.log'))

    if preexisting_file:
        with open(basename, 'w') as file:
            file.write('contents')
        jan_first = time.mktime(datetime(2010, 1, 1).timetuple())
        os.utime(basename, (jan_first, jan_first))

    handler = logbook.TimedRotatingFileHandler(
        basename,
        format_string='[{record.time:%H:%M}] {record.message}',
        backup_count=backup_count,
        rollover_format='{basename}{ext}.{timestamp}',
        timed_filename_for_current=False,
    )

    def fake_record(message, year, month, day, hour=0,
                    minute=0, second=0):
        lr = logbook.LogRecord('Test Logger', logbook.WARNING,
                               message)
        lr.time = datetime(year, month, day, hour, minute, second)
        return lr

    with activation_strategy(handler):
        for x in xrange(10):
            handler.handle(fake_record('First One', 2010, 1, 5, x + 1))
        for x in xrange(20):
            handler.handle(fake_record('Second One', 2010, 1, 6, x + 1))
        for x in xrange(10):
            handler.handle(fake_record('Third One', 2010, 1, 7, x + 1))
        for x in xrange(20):
            handler.handle(fake_record('Last One', 2010, 1, 8, x + 1))

    computed_files = [x for x in os.listdir(str(tmpdir)) if x.startswith('trot')]

    expected_files = ['trot.log.2010-01-01'] if preexisting_file else []
    expected_files += ['trot.log.2010-01-0{0}'.format(i) for i in xrange(5, 8)]
    expected_files += ['trot.log']
    expected_files = expected_files[-backup_count:]

    assert sorted(computed_files) == sorted(expected_files)

    with open(str(tmpdir.join('trot.log'))) as f:
        assert f.readline().rstrip() == '[01:00] Last One'
        assert f.readline().rstrip() == '[02:00] Last One'
    if backup_count > 1:
        with open(str(tmpdir.join('trot.log.2010-01-07'))) as f:
            assert f.readline().rstrip() == '[01:00] Third One'
            assert f.readline().rstrip() == '[02:00] Third One'
Example #3
0
def test_rotating_file_handler(logfile, activation_strategy, logger):
    basename = os.path.basename(logfile)
    handler = logbook.RotatingFileHandler(
        logfile,
        max_size=2048,
        backup_count=3,
    )
    handler.format_string = '{record.message}'
    with activation_strategy(handler):
        for c, x in zip(LETTERS, xrange(32)):
            logger.warn(c * 256)
    files = [
        x for x in os.listdir(os.path.dirname(logfile))
        if x.startswith(basename)
    ]
    files.sort()

    assert files == [
        basename, basename + '.1', basename + '.2', basename + '.3'
    ]
    with open(logfile) as f:
        assert f.readline().rstrip() == ('C' * 256)
        assert f.readline().rstrip() == ('D' * 256)
        assert f.readline().rstrip() == ('E' * 256)
        assert f.readline().rstrip() == ('F' * 256)
Example #4
0
    def calling_frame(self):
        """The frame in which the record has been created.  This only
        exists for as long the log record is not closed.
        """
        frm = self.frame
        globs = globals()
        while frm is not None and frm.f_globals is globs:
            frm = frm.f_back

        for _ in xrange(self.frame_correction):
            frm = frm.f_back

        return frm
Example #5
0
    def calling_frame(self):
        """The frame in which the record has been created.  This only
        exists for as long the log record is not closed.
        """
        frm = self.frame
        globs = globals()
        while frm is not None and frm.f_globals is globs:
            frm = frm.f_back

        for _ in helpers.xrange(self.frame_correction):
            frm = frm.f_back

        return frm
Example #6
0
def test_basic_ticketing(logger):
    from logbook.ticketing import TicketingHandler
    from time import sleep
    with TicketingHandler('sqlite:///') as handler:
        for x in xrange(5):
            logger.warn('A warning')
            sleep(0.2)
            logger.info('An error')
            sleep(0.2)
            if x < 2:
                try:
                    1 / 0
                except Exception:
                    logger.exception()

    assert handler.db.count_tickets() == 3
    tickets = handler.db.get_tickets()
    assert len(tickets) == 3
    assert tickets[0].level == logbook.INFO
    assert tickets[1].level == logbook.WARNING
    assert tickets[2].level == logbook.ERROR
    assert tickets[0].occurrence_count == 5
    assert tickets[1].occurrence_count == 5
    assert tickets[2].occurrence_count == 2
    assert tickets[0].last_occurrence.level == logbook.INFO

    tickets[0].solve()
    assert tickets[0].solved
    tickets[0].delete()

    ticket = handler.db.get_ticket(tickets[1].ticket_id)
    assert ticket == tickets[1]

    occurrences = handler.db.get_occurrences(tickets[2].ticket_id,
                                             order_by='time')
    assert len(occurrences) == 2
    record = occurrences[0]
    assert __file_without_pyc__ in record.filename
    # avoid 2to3 destroying our assertion
    assert getattr(record, 'func_name') == 'test_basic_ticketing'
    assert record.level == logbook.ERROR
    assert record.thread == get_ident()
    assert record.process == os.getpid()
    assert record.channel == 'testlogger'
    assert '1 / 0' in record.formatted_exception
Example #7
0
def test_rotating_file_handler(logfile, activation_strategy, logger):
    basename = os.path.basename(logfile)
    handler = logbook.RotatingFileHandler(logfile, max_size=2048,
                                          backup_count=3,
                                          )
    handler.format_string = '{record.message}'
    with activation_strategy(handler):
        for c, x in zip(LETTERS, xrange(32)):
            logger.warn(c * 256)
    files = [x for x in os.listdir(os.path.dirname(logfile))
             if x.startswith(basename)]
    files.sort()

    assert files == [basename, basename + '.1', basename + '.2', basename + '.3']
    with open(logfile) as f:
        assert f.readline().rstrip() == ('C' * 256)
        assert f.readline().rstrip() == ('D' * 256)
        assert f.readline().rstrip() == ('E' * 256)
        assert f.readline().rstrip() == ('F' * 256)
Example #8
0
def test_pickle(active_handler, logger):
    try:
        1 / 0
    except Exception:
        logger.exception()
        record = active_handler.records[0]
    record.pull_information()
    record.close()

    for p in xrange(pickle.HIGHEST_PROTOCOL):
        exported = pickle.dumps(record, p)
        imported = pickle.loads(exported)
        for key, value in iteritems(record.__dict__):
            if key[0] == '_':
                continue
            imported_value = getattr(imported, key)
            if isinstance(value, ZeroDivisionError):
                # in Python 3.2, ZeroDivisionError(x) != ZeroDivisionError(x)
                assert type(value) is type(imported_value)
                assert value.args == imported_value.args
            else:
                assert value == imported_value
Example #9
0
def test_pickle(active_handler, logger):
    try:
        1 / 0
    except Exception:
        logger.exception()
        record = active_handler.records[0]
    record.pull_information()
    record.close()

    for p in xrange(pickle.HIGHEST_PROTOCOL):
        exported = pickle.dumps(record, p)
        imported = pickle.loads(exported)
        for key, value in iteritems(record.__dict__):
            if key[0] == '_':
                continue
            imported_value = getattr(imported, key)
            if isinstance(value, ZeroDivisionError):
                # in Python 3.2, ZeroDivisionError(x) != ZeroDivisionError(x)
                assert type(value) is type(imported_value)
                assert value.args == imported_value.args
            else:
                assert value == imported_value