'Stream Flexget log Streams as line delimited JSON'

@api.doc(parser=server_log_parser)
@api.response(200, description=u'Streams    as    line    delimited    JSON')
def get(self, session=None):

    args = server_log_parser.parse_args()
    def follow(lines, search):
        log_parser = LogParser(search)
        stream_from_byte = 0
        lines_found = []
        if os.path.isabs(self.manager.options.logfile):
            base_log_file = self.manager.options.logfile
        else:
            base_log_file = os.path.join(self.manager.config_base, self.manager.options.logfile)
        (yield u'{"stream":    [')
        for i in range(0, 9):
            log_file = (u'%s.%s' % (base_log_file, i)).rstrip(u'.0')
            if (not os.path.isfile(log_file)):
                break
            with open(log_file, u'rb') as fh:
                fh.seek(0, 2)
                end_byte = fh.tell()
                if (i == 0):
                    stream_from_byte = end_byte
                if (len(lines_found) >= lines):
                    break
                for line in reverse_readline(fh, start_byte=end_byte):
                    if (len(lines_found) >= lines):
                        break
                    if log_parser.matches(line):
                        lines_found.append(log_parser.json_string(line))
                for l in reversed(lines_found):
                    (yield (l + u',\n'))
        current_inode = file_inode(base_log_file)
        while True:
            if (cherrypy.engine.state != cherrypy.engine.states.STARTED):
                break
            new_inode = file_inode(base_log_file)
            if (current_inode != new_inode):
                stream_from_byte = 0
                current_inode = new_inode
            try:
                with open(base_log_file, u'rb') as fh:
                    fh.seek(stream_from_byte)
                    line = fh.readline().decode(sys.getfilesystemencoding())
                    stream_from_byte = fh.tell()
            except IOError:
                (yield u'{}')
                continue
            line = (log_parser.json_string(line) if log_parser.matches(line) else u'{}')
            if (line == u'{}'):
                sleep(2)
            (yield (line + u',\n'))
        (yield u'{}]}')
    return Response(follow(args[u'lines'], args[u'search']), mimetype=u'text/event-stream')
