import logging
from typing import Callable


class CustomCallbackHandler(logging.Handler):
    """
    A handler class that calls a custom callback. This is used to send error notifications to the control process.
    """

    def __init__(self, callback: Callable[[str], None], level=logging.ERROR):
        logging.Handler.__init__(self, level)
        self._callback = callback

    def emit(self, record):
        try:
            msg = self.format(record)
            self._callback(msg)
        except RecursionError:  # See issue 36272
            raise
        except Exception:
            self.handleError(record)

    def __repr__(self):
        level = logging.getLevelName(self.level)
        return "<%s (%s)>" % (self.__class__.__name__, level)
