log.py 2.64 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
"""
    Copyright (c) 2015 Ad Schellevis
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.

    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
"""
26

27 28
import os

29 30

def reverse_log_reader(filename, block_size=8192, start_pos=None):
31 32 33
    """ read log file in reverse order
    :param filename: filename to parse
    :param block_size: max block size to examine per loop
34
    :param start_pos: start at position in file (None is end of file)
35 36
    :return: generator
    """
37
    with open(filename, 'rU') as f_in:
38 39 40 41 42
        if start_pos is None:
            f_in.seek(0, os.SEEK_END)
            file_byte_start = f_in.tell()
        else:
            file_byte_start = start_pos
43 44 45

        data = ''
        while True:
46
            if file_byte_start - block_size < 0:
47
                block_size = file_byte_start
48 49 50 51 52 53
                file_byte_start = 0
            else:
                file_byte_start -= block_size

            f_in.seek(file_byte_start)

54
            data = f_in.read(block_size) + data
55
            eol = data.rfind('\n')
56

57
            while eol > -1:
58
                line_end = file_byte_start + len(data)
59 60 61
                line = data[eol:]
                data = data[:eol]
                eol = data.rfind('\n')
62
                # field line and position in file
63
                yield {'line': line.strip(), 'pos': line_end}
64 65
            if file_byte_start == 0 and eol == -1:
                # flush last line
66
                yield {'line': data.strip(), 'pos': len(data)}
67 68 69

            if file_byte_start == 0:
                break