当前位置: 首页>>代码示例>>Python>>正文


Python logging.RootLogger方法代码示例

本文整理汇总了Python中logging.RootLogger方法的典型用法代码示例。如果您正苦于以下问题:Python logging.RootLogger方法的具体用法?Python logging.RootLogger怎么用?Python logging.RootLogger使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在logging的用法示例。


在下文中一共展示了logging.RootLogger方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: hook_exceptions

# 需要导入模块: import logging [as 别名]
# 或者: from logging import RootLogger [as 别名]
def hook_exceptions(self, logger: logging.RootLogger) -> None:
        """Format excetion traceback.
        
        Parameters:
            logger:
                The logger for logging exceptions.
        """

        def _hook(exc_type, value, exc_tb) -> None:
            nest_dir = os.path.dirname(os.path.abspath(__file__))
            traceback_str = ''
            idx = 0
            for file_name, line_number, func_name, text in traceback.extract_tb(exc_tb)[1:]:
                # skip Nest-related tracebacks to make it more readable
                if os.path.dirname(os.path.abspath(file_name)) == nest_dir:
                    continue
                idx += 1
                traceback_str += '\n  [%d] File "%s", line %d, in function "%s"\n    %s' % \
                    (idx, file_name, line_number, func_name, text)
            if traceback_str != '':
                traceback_str = 'Traceback: ' + traceback_str
            logger.critical('Exception occurred during resolving:\nType: %s\nMessage: %s\n%s' % \
                (exc_type.__name__, value, traceback_str))

        sys.excepthook = _hook 
开发者ID:ZhouYanzhao,项目名称:Nest,代码行数:27,代码来源:cli.py

示例2: test_log_config_is_loaded___logger_is_updated

# 需要导入模块: import logging [as 别名]
# 或者: from logging import RootLogger [as 别名]
def test_log_config_is_loaded___logger_is_updated(self, level):
        log_file_path = os.path.abspath(os.path.join("tmp", "log_file.txt"))
        with patch('logging.root', logging.RootLogger(logging.NOTSET)):
            read_log_config({
                'LOG_FILE': log_file_path,
                'LOG_LEVEL': level,
                'LOG_MAX_SIZE_IN_BYTES': 100,
                'LOG_BACKUP_COUNT': 10,
            })

            logger = logging.getLogger()

            self.assertEqual(level, logger.level)

            self.assertEqual(1, len(logger.handlers))
            handler = logger.handlers[0]
            self.assertIsInstance(handler, RotatingFileHandler)
            self.assertEqual(log_file_path, handler.baseFilename)
            self.assertEqual(100, handler.maxBytes)
            self.assertEqual(10, handler.backupCount) 
开发者ID:OasisLMF,项目名称:OasisLMF,代码行数:22,代码来源:test_log.py

示例3: resetLogging

# 需要导入模块: import logging [as 别名]
# 或者: from logging import RootLogger [as 别名]
def resetLogging():
    """ Reset the handlers and loggers so that we
    can rerun the tests starting from a blank slate.
    """
    __pragma__("skip")
    logging._handlerList = []

    import weakref
    logging._handlers = weakref.WeakValueDictionary()

    logging.root = logging.RootLogger(logging.WARNING)
    logging.Logger.root = logging.root
    logging.Logger.manager = logging.Manager(logging.root)
    logging.root.manager = logging.Logger.manager
    __pragma__("noskip")

    if __envir__.executor_name == __envir__.transpiler_name:
        logging._resetLogging() 
开发者ID:QQuick,项目名称:Transcrypt,代码行数:20,代码来源:utils.py

示例4: configure_stream

# 需要导入模块: import logging [as 别名]
# 或者: from logging import RootLogger [as 别名]
def configure_stream(level='WARNING'):
    """Configure root logger using a standard stream handler.

    Args:
        level (string, optional): lowest level to log to the console

    Returns:
        logging.RootLogger: root logger instance with attached handler
    """
    # get the root logger
    root_logger = logging.getLogger()
    # set the logger level to the same as will be used by the handler
    root_logger.setLevel(level)

    # customize formatter, align each column
    template = "[%(asctime)s] %(name)-25s %(levelname)-8s %(message)s"
    formatter = logging.Formatter(template)

    # add a basic STDERR handler to the logger
    console = logging.StreamHandler()
    console.setLevel(level)
    console.setFormatter(formatter)

    root_logger.addHandler(console)
    return root_logger 
开发者ID:robinandeer,项目名称:puzzle,代码行数:27,代码来源:log.py

示例5: setup_logger

# 需要导入模块: import logging [as 别名]
# 或者: from logging import RootLogger [as 别名]
def setup_logger() -> logging.RootLogger:
    """Initialize logger.

    Returns:
        The global logger
    """

    # set up logger
    logger = logging.getLogger('Nest')
    logger.setLevel(logging.DEBUG)
    # create a formatter and add it to the handlers
    screen_formatter = logging.Formatter('%(message)s')
    # create a console handler
    screen_handler = logging.StreamHandler()
    screen_handler.setLevel(logging.INFO)
    screen_handler.setFormatter(screen_formatter)
    screen_handler.addFilter(ExceptionFilter())
    logger.addHandler(screen_handler)
    if settings['LOGGING_TO_FILE']:
        # create a file handler which logs warning and error messages
        file_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        file_handler = logging.FileHandler(settings['LOGGING_PATH'], encoding='utf8')
        file_handler.setLevel(logging.WARNING)
        file_handler.setFormatter(file_formatter)
        logger.addHandler(file_handler)

    return logger 
开发者ID:ZhouYanzhao,项目名称:Nest,代码行数:29,代码来源:logger.py

示例6: get_logger

# 需要导入模块: import logging [as 别名]
# 或者: from logging import RootLogger [as 别名]
def get_logger():
    """
    Returns the application's logger instance by name.

    :rtype: logging.Logger.
    :return: logger instance.
    """
    _logger = logging.getLogger(APP_NAME)

    if isinstance(_logger, logging.RootLogger):
        _logger = make_logger()

    return _logger 
开发者ID:aalhour,项目名称:cookiecutter-aiohttp-sqlalchemy,代码行数:15,代码来源:logger.py

示例7: logging_sandbox

# 需要导入模块: import logging [as 别名]
# 或者: from logging import RootLogger [as 别名]
def logging_sandbox():
    # Monkeypatch a replacement root logger, so that our changes to logging
    # configuration don't persist outside of the test
    root_logger = logging.RootLogger(logging.WARNING)

    with mock.patch.object(logging, "root", root_logger):
        with mock.patch.object(logging.Logger, "root", root_logger):
            with mock.patch.object(
                logging.Logger, "manager", logging.Manager(root_logger)
            ):
                yield 
开发者ID:canonical,项目名称:ubuntu-advantage-client,代码行数:13,代码来源:conftest.py

示例8: test_rotating_log_config_is_loaded___logger_is_set

# 需要导入模块: import logging [as 别名]
# 或者: from logging import RootLogger [as 别名]
def test_rotating_log_config_is_loaded___logger_is_set(self, level):
        log_file_path = os.path.abspath(os.path.join("tmp", "log_file.txt"))
        with patch('logging.root', logging.RootLogger(logging.NOTSET)):
            set_rotating_logger(log_file_path=log_file_path, log_level=level, max_file_size=100, max_backups=10)

            logger = logging.getLogger()

            self.assertEqual(level, logger.level)

            self.assertEqual(1, len(logger.handlers))
            handler = logger.handlers[0]
            self.assertIsInstance(handler, RotatingFileHandler)
            self.assertEqual(log_file_path, handler.baseFilename)
            self.assertEqual(100, handler.maxBytes)
            self.assertEqual(10, handler.backupCount) 
开发者ID:OasisLMF,项目名称:OasisLMF,代码行数:17,代码来源:test_log.py

示例9: setUp

# 需要导入模块: import logging [as 别名]
# 或者: from logging import RootLogger [as 别名]
def setUp(self):
        self._orig_root_logger = logging.root
        logging.root = logging.RootLogger(logging.WARNING) 
开发者ID:OasisLMF,项目名称:OasisLMF,代码行数:5,代码来源:test_base.py

示例10: __init__

# 需要导入模块: import logging [as 别名]
# 或者: from logging import RootLogger [as 别名]
def __init__(self, sensor_wrapper):
        self._sensor_wrapper = sensor_wrapper

        # Holds a mock logger instance
        # We use a Mock class so use can assert logger was called with particular arguments
        self._logger = Mock(spec=RootLogger)

        # Holds a list of triggers which were dispatched
        self.dispatched_triggers = []

        self._datastore_service = MockDatastoreService(logger=self._logger,
                                                       pack_name=self._sensor_wrapper._pack,
                                                       class_name=self._sensor_wrapper._class_name) 
开发者ID:StackStorm,项目名称:st2,代码行数:15,代码来源:sensor.py

示例11: __init__

# 需要导入模块: import logging [as 别名]
# 或者: from logging import RootLogger [as 别名]
def __init__(self, action_wrapper):
        self._action_wrapper = action_wrapper

        # Holds a mock logger instance
        # We use a Mock class so use can assert logger was called with particular arguments
        self._logger = Mock(spec=RootLogger)

        self._datastore_service = MockDatastoreService(logger=self._logger,
                                                       pack_name=self._action_wrapper._pack,
                                                       class_name=self._action_wrapper._class_name) 
开发者ID:StackStorm,项目名称:st2,代码行数:12,代码来源:action.py

示例12: reset_logger

# 需要导入模块: import logging [as 别名]
# 或者: from logging import RootLogger [as 别名]
def reset_logger():
    def reset():
        loguru.logger.remove()
        loguru.logger.__init__(
            loguru._logger.Core(), None, 0, False, False, False, False, True, None, {}
        )
        loguru._logger.context.set({})
        logging.Logger.manager.loggerDict.clear()
        logging.root = logging.RootLogger("WARNING")

    reset()
    yield
    reset() 
开发者ID:Delgan,项目名称:loguru,代码行数:15,代码来源:conftest.py

示例13: get_logger

# 需要导入模块: import logging [as 别名]
# 或者: from logging import RootLogger [as 别名]
def get_logger(path):
    """
    Returns a logger object that writes a log file to disk ( provided path )
    and to the stderr output.

    :param str path:
    :return: Logger
    :rtype: logging.RootLogger
    """

    # get logger
    global logger
    logger = logging.getLogger()

    # create logging file
    if path:
        logging_path = os.path.join(path, "log.log")
        logging.basicConfig(
            filename=logging_path,
            level=logging.DEBUG,
            format="%(asctime)s | %(levelname)s | %(message)s",
            datefmt="%Y/%m/%d/ %I:%M:%S",
        )
    
    # create logging to stderr
    stderr_logger = logging.StreamHandler()
    stderr_logger.setLevel(logging.INFO)
    stderr_logger.setFormatter(
        logging.Formatter("%(levelname)s | %(message)s")
    )

    logger.addHandler(stderr_logger)

    return logger 
开发者ID:robertjoosten,项目名称:video2mocap,代码行数:36,代码来源:logging.py

示例14: get_maya_logger

# 需要导入模块: import logging [as 别名]
# 或者: from logging import RootLogger [as 别名]
def get_maya_logger(path):
    """
    Returns a logger object that writes a log file to disk ( provided path )
    and to the stderr output.

    :param str path:
    :return: Logger
    :rtype: logging.RootLogger
    """
    # get logger
    global logger
    logger = logging.getLogger()

    # remove existing handlers
    for handler in logger.handlers:
        logger.removeHandler(handler)

    # create logging file
    if path:
        logging_path = os.path.join(path, "log.log")
        file_logger = logging.FileHandler(logging_path)
        file_logger.setLevel(logging.DEBUG)
        file_logger.setFormatter(
            logging.Formatter(
                "%(asctime)s | %(levelname)s | %(message)s",
                "%Y/%m/%d/ %I:%M:%S"
            )
        )

        logger.addHandler(file_logger)

    # create logging to stderr
    stderr_logger = logging.StreamHandler()
    stderr_logger.setLevel(logging.INFO)
    stderr_logger.setFormatter(
        logging.Formatter("%(levelname)s | %(message)s")
    )

    logger.addHandler(stderr_logger)

    return logger 
开发者ID:robertjoosten,项目名称:video2mocap,代码行数:43,代码来源:logging.py

示例15: get_data

# 需要导入模块: import logging [as 别名]
# 或者: from logging import RootLogger [as 别名]
def get_data(filepath: str, compress: bool = False,
             redis_client: Optional[StrictRedis] = None,
             redis_key_prefix: Optional[str] = None,
             logger: Optional[logging.RootLogger] = None) -> Dict[str, List[str]]:
    data_json = None
    filename = os.path.basename(filepath)
    if redis_client and redis_key_prefix:
        key = redis_key_prefix.format(filename)
        try:
            data_json = redis_client.get(key)
        except Exception:
            if logger:
                logger.exception('Unable to get the search graph words from Redis.')
            else:
                print('Unable to get the search graph words from Redis.')
        if data_json:
            data_json = gzip.decompress(data_json).decode('utf-8')
    if not data_json:
        data_json = read_local_dump(filepath)
    data = json.loads(data_json)

    if compress:
        hash_to_val = {}

        for word, value in data.items():
            context, display, count = value
            display = _simple_compress(item=display, hash_to_val=hash_to_val)
            for key, val in context.items():
                context[key] = _simple_compress(
                    item=context[key], hash_to_val=hash_to_val
                )
            data[word] = WordValue(context=context, display=display, count=count)

    return data 
开发者ID:seperman,项目名称:fast-autocomplete,代码行数:36,代码来源:loader.py


注:本文中的logging.RootLogger方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。