#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging

import saas.protos.sti_report_pb2 as yt_report
import google.protobuf.text_format as text_format


class ReportHandler(logging.Handler):
    def __init__(self, report_file_name, level=logging.ERROR):
        logging.Handler.__init__(self)
        self.level = level
        self.report_file = open(report_file_name, 'a')
        self.report = yt_report.TYTReportProto()
        self.formatter = None

    def handle(self, record):
        if record.levelno >= self.level:
            self.report.Error[:] = [self.formatter.format(record)]
            serialized = text_format.MessageToString(self.report)
            self.report_file.write(serialized)
            self.report_file.flush()

    def setFormatter(self, formatter):
        self.formatter = formatter

    def close(self):
        self.report_file.close()
