Example #1
0
    def on_settings_changed() -> None:
        """

        :return:
        """
        logging_level = CriticalSettings.get_logging_level()
        root_logger = Logger.get_root_logger()
        root_logger.setLevel(logging_level)
Example #2
0
    def get_root_logger():
        # type: () -> Logger
        """

        :return:
        """
        if Logger._root_logger is None:
            logging.setLoggerClass(LazyLogger)
            root_logger = logging.RootLogger(Logger.DEBUG)
            root_logger = logging.root
            root_logger.addHandler(MyHandler())
            logging_level = CriticalSettings.get_logging_level()
            xbmc.log('get_root_logger logging_level: ' + str(logging_level),
                     xbmc.LOGDEBUG)
            root_logger.setLevel(logging_level)
            Trace.enable_all()
            root_logger.addFilter(Trace())
            Logger._root_logger = root_logger
        return Logger._root_logger
Example #3
0
class MyFormatter(logging.Formatter):
    """

    """

    INCLUDE_THREAD_INFO = CriticalSettings.is_debug_include_thread_info()

    def __init__(self, fmt: str = None, datefmt: str = None) -> None:
        """

        :param fmt:
        :param datefmt:
        :param style:
        """
        super().__init__(fmt=fmt, datefmt=datefmt)

    def format(self, record: logging.LogRecord) -> str:
        """

        :param record:
        :return:
        """
        """
            Attribute name 	Format 	Description
            args 	You shouldn’t need to format this yourself. 	The tuple of arguments merged into msg to produce message, or a dict whose values are used for the merge (when there is only one argument, and it is a dictionary).
            asctime 	%(asctime)s 	Human-readable time when the LogRecord was created. By default this is of the form ‘2003-07-08 16:49:45,896’ (the numbers after the comma are millisecond portion of the time).
            created 	%(created)f 	Time when the LogRecord was created (as returned by time.time()).
            exc_info 	You shouldn’t need to format this yourself. 	Exception tuple (à la sys.exc_info) or, if no exception has occurred, None.
            filename 	%(filename)s 	Filename portion of pathname.
            funcName 	%(funcName)s 	Name of function containing the logging call.
            levelname 	%(levelname)s 	Text logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').
            levelno 	%(levelno)s 	Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL).
            lineno 	%(lineno)d 	Source line number where the logging call was issued (if available).
            module 	%(module)s 	Module (name portion of filename).
            msecs 	%(msecs)d 	Millisecond portion of the time when the LogRecord was created.
            message 	%(message)s 	The logged message, computed as msg % args. This is set when Formatter.format() is invoked.
            msg 	You shouldn’t need to format this yourself. 	The format string passed in the original logging call. Merged with args to produce message, or an arbitrary object (see Using arbitrary objects as messages).
            name 	%(name)s 	Name of the config_logger used to log the call.
            pathname 	%(pathname)s 	Full pathname of the source file where the logging call was issued (if available).
            process 	%(process)d 	Process ID (if available).
            processName 	%(processName)s 	Process name (if available).
            relativeCreated 	%(relativeCreated)d 	Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.
            stack_info 	You shouldn’t need to format this yourself. 	Stack frame information (where available) from the bottom of the stack in the current thread, up to and including the stack frame of the logging call which resulted in the creation of this record.
            thread 	%(thread)d 	Thread ID (if available).
            threadName 	%(threadName)s 	Thread name (if available).
            
            [service.randomtrailers.backend:DiscoverTmdbMovies:process_page] 
            [service.randomtrailers.backend:FolderMovieData:add_to_discovered_trailers  TRACE_DISCOVERY]
        """
        # threadName Constants.CURRENT_ADDON_SHORT_NAME funcName:lineno
        # [threadName name funcName:lineno]

        text = ''
        try:
            start_file = record.__dict__.get('start_file', None)
            try:
                pathname, lineno, func = start_file
            except ValueError:
                pathname, lineno, func = "(unknown file)", 0, "(unknown function)"

            record.pathname = pathname
            try:
                record.filename = os.path.basename(pathname)
                record.module = os.path.splitext(record.filename)[0]
            except (TypeError, ValueError, AttributeError):
                record.filename = pathname
                record.module = "Unknown module"
            record.lineno = lineno
            record.funcName = func

            suffix = super().format(record)
            passed_traces = record.__dict__.get('trace_string', None)
            if passed_traces is None:
                if type(self).INCLUDE_THREAD_INFO:
                    prefix = '[Thread {!s} {!s}.{!s}:{!s}:{!s}]'.format(
                        record.threadName, record.name, record.funcName,
                        record.lineno, record.levelname)
                else:
                    prefix = '[{!s}.{!s}:{!s}]'.format(record.name,
                                                       record.funcName,
                                                       record.lineno)
            else:
                if type(self).INCLUDE_THREAD_INFO:
                    prefix = '[Thread {!s} {!s}.{!s}:{!s}:{!s} Trace:{!s}]'.format(
                        record.threadName, record.name, record.funcName,
                        record.lineno, record.levelname, passed_traces)
                else:
                    prefix = '[{!s}.{!s}:{!s}:{!s} Trace:{!s}]'.format(
                        record.name, record.funcName, record.lineno,
                        record.levelname, passed_traces)
            text = '{} {}'.format(prefix, suffix)
        except Exception as e:
            pass

        return text

    def formatException(self,
                        ei: List[Any] = None,
                        ignore_frames: int = 0) -> str:
        """

        :param ei:
        :param ignore_frames:
        :return:
        """
        ignore_frames += 1
        if ei is not None:
            thread_name = threading.current_thread().getName()

            sio = StringIO()
            self.print_exception(ei[0],
                                 ei[1],
                                 ei[2],
                                 thread_name='',
                                 limit=None,
                                 log_file=sio)

            s = sio.getvalue()
            sio.close()
            return s

    def print_exception(self,
                        etype: Type,
                        value: Any,
                        tb: Any,
                        thread_name: str = '',
                        limit: int = None,
                        log_file: StringIO = None) -> None:
        """

        :param tb:
        :param thread_name:
        :param limit:
        :param log_file:
        :return:
        """

        if tb is None:
            tb = sys.exc_info()[2]

        if log_file is None:
            log_file = sys.stderr

        lines = [
            'LEAK Traceback StackTrace StackDump (most recent call last)\n'
        ]

        for item in reversed(inspect.getouterframes(tb.tb_frame)[1:]):
            lines.append('File "{1}", line {2}, in {3}\n'.format(*item))
            for line in item[4]:
                lines.append(' ' + line.lstrip())

        if hasattr(tb, 'tb_frame'):
            for item in inspect.getinnerframes(tb):
                lines.append(' File "{1}", line {2}, in {3}\n'.format(*item))
                for line in item[4]:
                    lines.append(' ' + line.lstrip())

        lines = lines + traceback.format_exception_only(etype, value)

        for line in lines:
            log_file.write(line)