

import syslog
import logging


def file_logger(filename):
    """Create a logger. This sucks, the logging module sucks, but
    it'll do for now.
    """
    handler = logging.FileHandler(filename)
    formatter = logging.Formatter()
    handler.setFormatter(formatter)
    log = logging.getLogger(filename)
    log.addHandler(handler)
    log.setLevel(logging.DEBUG)
    return log, handler


class LineLogger(object):
    towrite = ''
    def __init__(self, emit=None):
        self.emit = emit

    def write(self, stuff):
        self.towrite += stuff
        if '\n' in self.towrite:
            self.flush()

    def flush(self):
        try:
            newline = self.towrite.index('\n')
        except ValueError:
            newline = len(self.towrite)
        while True:
            self.emit(self.towrite[:newline])
            self.towrite = self.towrite[newline+1:]
            try:
                newline = self.towrite.index('\n')
            except ValueError:
                break

    def close(self):
        pass


class SysLogger(LineLogger):
    """A file-like object which writes to syslog. Can be inserted
    as sys.stdin and sys.stderr to have logging output redirected
    to syslog.
    """
    def __init__(self, priority):
        self.priority = priority

    def emit(self, line):
        syslog.syslog(self.priority, line)


class TeeLogger(LineLogger):
    def __init__(self, one, two):
        self.one, self.two = one, two

    def emit(self, line):
        self.one.emit(line)
        self.two.emit(line)


class FileLogger(LineLogger):
    def __init__(self, file):
        self.file = file

    def emit(self, line):
        self.file.write(line)

