import psycopg2, logging

class PgLog(logging.StreamHandler):
    def __init__(self, host, port, dbname, user, password):
        super().__init__()
        
        self.host = host
        self.port = port
        self.dbname = dbname
        self.user = user
        self.password = password

        self.conn = psycopg2.connect(
            database = dbname,
            user = user,
            password = password,
            host = host,
            port = port
        )

        self.cursor = self.conn.cursor()

    def __del__(self):
        self.cursor.close()
        self.conn.close()

    def emit(self, record):
        self.cursor.execute(
            f"INSERT INTO logs (level, message) VALUES (%s, %s)",
            (
                record.levelname,
                record.getMessage(),
            )
        )
        self.conn.commit()