コード例 #1
0
def setup_console_handler(log_level=None, log_format=None, date_format=None):
    """
    Setup the console stream handler
    """
    if is_console_handler_configured():
        log.warning("Console logging already configured")
        return

    atexit.register(shutdown_console_handler)

    log.trace(
        "Setting up console logging: %s",
        dict(log_level=log_level,
             log_format=log_format,
             date_format=date_format),
    )

    if log_level is None:
        log_level = logging.WARNING

    log_level = get_logging_level_from_string(log_level)

    set_log_record_factory(SaltColorLogRecord)

    handler = None
    for handler in logging.root.handlers:
        if handler is get_temp_handler():
            continue

        if not hasattr(handler, "stream"):
            # Not a stream handler, continue
            continue

        if handler.stream is sys.stderr:
            # There's already a logging handler outputting to sys.stderr
            break
    else:
        handler = StreamHandler(sys.stderr)
    handler.setLevel(log_level)

    # Set the default console formatter config
    if not log_format:
        log_format = DFLT_LOG_FMT_CONSOLE
    if not date_format:
        date_format = DFLT_LOG_DATEFMT

    formatter = logging.Formatter(log_format, datefmt=date_format)

    handler.setFormatter(formatter)
    logging.root.addHandler(handler)

    setup_console_handler.__handler__ = handler
コード例 #2
0
def setup_console_logger(log_level='error', log_format=None, date_format=None):
    '''
    Setup the console logger
    '''
    if is_console_configured():
        logging.getLogger(__name__).warning(
            'Console logging already configured')
        return

    # Remove the temporary logging handler
    __remove_temp_logging_handler()

    if log_level is None:
        log_level = 'warning'

    level = LOG_LEVELS.get(log_level.lower(), logging.ERROR)

    setLogRecordFactory(SaltColorLogRecord)

    handler = None
    for handler in logging.root.handlers:
        if handler is LOGGING_STORE_HANDLER:
            continue

        if not hasattr(handler, 'stream'):
            # Not a stream handler, continue
            continue

        if handler.stream is sys.stderr:
            # There's already a logging handler outputting to sys.stderr
            break
    else:
        handler = StreamHandler(sys.stderr)
    handler.setLevel(level)

    # Set the default console formatter config
    if not log_format:
        log_format = '[%(levelname)-8s] %(message)s'
    if not date_format:
        date_format = '%H:%M:%S'

    formatter = logging.Formatter(log_format, datefmt=date_format)

    handler.setFormatter(formatter)
    logging.root.addHandler(handler)

    global __CONSOLE_CONFIGURED
    global __LOGGING_CONSOLE_HANDLER
    __CONSOLE_CONFIGURED = True
    __LOGGING_CONSOLE_HANDLER = handler
コード例 #3
0
    def test_exc_info_on_loglevel(self):
        def raise_exception_on_purpose():
            1 / 0  # pylint: disable=pointless-statement

        log = SaltLoggingClass(__name__)

        # Only stream2 should contain the traceback
        stream1 = io.StringIO()
        stream2 = io.StringIO()
        handler1 = StreamHandler(stream1)
        handler2 = StreamHandler(stream2)

        handler1.setLevel(logging.INFO)
        handler2.setLevel(logging.DEBUG)

        log.addHandler(handler1)
        log.addHandler(handler2)

        try:
            raise_exception_on_purpose()
        except ZeroDivisionError as exc:
            log.error(
                "Exception raised on purpose caught: ZeroDivisionError",
                exc_info_on_loglevel=logging.DEBUG,
            )

        try:
            self.assertIn(
                "Exception raised on purpose caught: ZeroDivisionError",
                stream1.getvalue(),
            )
            self.assertNotIn("Traceback (most recent call last)",
                             stream1.getvalue())
            self.assertIn(
                "Exception raised on purpose caught: ZeroDivisionError",
                stream2.getvalue(),
            )
            self.assertIn("Traceback (most recent call last)",
                          stream2.getvalue())
        finally:
            log.removeHandler(handler1)
            log.removeHandler(handler2)

        # Both streams should contain the traceback
        stream1 = io.StringIO()
        stream2 = io.StringIO()
        handler1 = StreamHandler(stream1)
        handler2 = StreamHandler(stream2)

        handler1.setLevel(logging.INFO)
        handler2.setLevel(logging.DEBUG)

        log.addHandler(handler1)
        log.addHandler(handler2)

        try:
            raise_exception_on_purpose()
        except ZeroDivisionError as exc:
            log.error(
                "Exception raised on purpose caught: ZeroDivisionError",
                exc_info_on_loglevel=logging.INFO,
            )

        try:
            self.assertIn(
                "Exception raised on purpose caught: ZeroDivisionError",
                stream1.getvalue(),
            )
            self.assertIn("Traceback (most recent call last)",
                          stream1.getvalue())
            self.assertIn(
                "Exception raised on purpose caught: ZeroDivisionError",
                stream2.getvalue(),
            )
            self.assertIn("Traceback (most recent call last)",
                          stream2.getvalue())
        finally:
            log.removeHandler(handler1)
            log.removeHandler(handler2)

        # No streams should contain the traceback
        stream1 = io.StringIO()
        stream2 = io.StringIO()
        handler1 = StreamHandler(stream1)
        handler2 = StreamHandler(stream2)

        handler1.setLevel(logging.ERROR)
        handler2.setLevel(logging.INFO)

        log.addHandler(handler1)
        log.addHandler(handler2)

        try:
            raise_exception_on_purpose()
        except ZeroDivisionError as exc:
            log.error(
                "Exception raised on purpose caught: ZeroDivisionError",
                exc_info_on_loglevel=logging.DEBUG,
            )

        try:
            self.assertIn(
                "Exception raised on purpose caught: ZeroDivisionError",
                stream1.getvalue(),
            )
            self.assertNotIn("Traceback (most recent call last)",
                             stream1.getvalue())
            self.assertIn(
                "Exception raised on purpose caught: ZeroDivisionError",
                stream2.getvalue(),
            )
            self.assertNotIn("Traceback (most recent call last)",
                             stream2.getvalue())
        finally:
            log.removeHandler(handler1)
            log.removeHandler(handler2)