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


Python logging.Logger方法代码示例

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


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

示例1: _warn_if_unused

# 需要导入模块: import logging [as 别名]
# 或者: from logging import Logger [as 别名]
def _warn_if_unused(config: Config, logger: Logger):
    """Warn if there are unused databases or metrics defined."""
    used_dbs: Set[str] = set()
    used_metrics: Set[str] = set()
    for query in config.queries.values():
        used_dbs.update(query.databases)
        used_metrics.update(metric.name for metric in query.metrics)

    unused_dbs = sorted(set(config.databases) - used_dbs)
    if unused_dbs:
        logger.warning(
            f"unused entries in \"databases\" section: {', '.join(unused_dbs)}"
        )
    unused_metrics = sorted(set(config.metrics) - GLOBAL_METRICS - used_metrics)
    if unused_metrics:
        logger.warning(
            f"unused entries in \"metrics\" section: {', '.join(unused_metrics)}"
        ) 
开发者ID:albertodonato,项目名称:query-exporter,代码行数:20,代码来源:config.py

示例2: get_logger

# 需要导入模块: import logging [as 别名]
# 或者: from logging import Logger [as 别名]
def get_logger(name=None):
    # type: (str) -> _logging.Logger
    """
    Return a logger with the specified name, creating it if necessary.

    If no name is specified, return the root logger.
    """
    global _logger

    if name == None or name == "":

        # Configure it the first time
        if _logger == None:
            _logger = _setup_logging(LOG_DEFAULT_SCOPE)

        return _logger
    else:
        return _setup_logging(name)

# ============================================================================= 
开发者ID:codepost-io,项目名称:codepost-python,代码行数:22,代码来源:custom_logging.py

示例3: log_

# 需要导入模块: import logging [as 别名]
# 或者: from logging import Logger [as 别名]
def log_(
    message: str,
    logger: logging.Logger,
    level: str = "info",
    extra: Optional[Dict] = None,
    trim: bool = False,
) -> None:
    """
    Log a request or response

    Args:
        message: JSON-RPC request or response string.
        level: Log level.
        extra: More details to include in the log entry.
        trim: Abbreviate log messages.
    """
    if extra is None:
        extra = {}
    # Clean up the message for logging
    if message:
        message = message.replace("\n", "").replace("  ", " ").replace("{ ", "{")
    if trim:
        message = _trim_message(message)
    # Log.
    getattr(logger, level)(message, extra=extra) 
开发者ID:bcb,项目名称:jsonrpcclient,代码行数:27,代码来源:log.py

示例4: enable_pretty_logging

# 需要导入模块: import logging [as 别名]
# 或者: from logging import Logger [as 别名]
def enable_pretty_logging(logger='calmjs', level=logging.DEBUG, stream=None):
    """
    Shorthand to enable pretty logging
    """

    def cleanup():
        logger.removeHandler(handler)
        logger.level = old_level

    if not isinstance(logger, logging.Logger):
        logger = logging.getLogger(logger)

    old_level = logger.level
    handler = logging.StreamHandler(stream)
    handler.setFormatter(logging.Formatter(
        u'%(asctime)s %(levelname)s %(name)s %(message)s'))
    logger.addHandler(handler)
    logger.setLevel(level)
    return cleanup 
开发者ID:calmjs,项目名称:calmjs,代码行数:21,代码来源:utils.py

示例5: __init__

# 需要导入模块: import logging [as 别名]
# 或者: from logging import Logger [as 别名]
def __init__(
        self,
        credential_provider: SimpleCredentialProvider,
        skill_conversation_id_factory: ConversationIdFactoryBase,
        channel_provider: ChannelProvider = None,
        logger: Logger = None,
    ):
        if not skill_conversation_id_factory:
            raise TypeError(
                "SkillHttpClient(): skill_conversation_id_factory can't be None"
            )

        super().__init__(credential_provider)

        self._skill_conversation_id_factory = skill_conversation_id_factory
        self._channel_provider = channel_provider 
开发者ID:microsoft,项目名称:botbuilder-python,代码行数:18,代码来源:skill_http_client.py

示例6: _EventLogUpload

# 需要导入模块: import logging [as 别名]
# 或者: from logging import Logger [as 别名]
def _EventLogUpload(self, source_log: Text):
    """Upload the log file contents to the local EventLog."""
    event_handler = logging.handlers.NTEventLogHandler('GlazierBuildLog')
    logger = logging.Logger('eventlogger')
    logger.addHandler(event_handler)
    logger.setLevel(logging.DEBUG)

    try:
      with open(source_log, 'r') as f:
        content = f.readlines()
        for line in content:
          logger.info(line)
    except IOError:
      raise LogCopyError(
          'Unable to open log file. It will not be imported into '
          'the Windows Event Log.') 
开发者ID:google,项目名称:glazier,代码行数:18,代码来源:log_copy.py

示例7: __init__

# 需要导入模块: import logging [as 别名]
# 或者: from logging import Logger [as 别名]
def __init__(
        self,
        plugin_dir_list: List[str],
        plugin_opts: Optional[Dict[str, Dict]] = None,
        stoq_config: Optional[helpers.StoqConfigParser] = None,
    ) -> None:
        self._stoq_config = stoq_config
        self._plugin_opts = {} if plugin_opts is None else plugin_opts
        self._plugin_name_to_info: Dict[str, Tuple[str, helpers.StoqConfigParser]] = {}
        self._loaded_plugins: Dict[str, BasePlugin] = {}
        self._loaded_provider_plugins: Dict[str, ProviderPlugin] = {}
        self._loaded_worker_plugins: Dict[str, WorkerPlugin] = {}
        self._loaded_source_archiver_plugins: Dict[str, ArchiverPlugin] = {}
        self._loaded_dest_archiver_plugins: Dict[str, ArchiverPlugin] = {}
        self._loaded_dispatcher_plugins: Dict[str, DispatcherPlugin] = {}
        self._loaded_connector_plugins: List[ConnectorPlugin] = []
        self._loaded_decorator_plugins: Dict[str, DecoratorPlugin] = {}

        if not hasattr(self, 'log') or self.log is None:
            self.log: logging.Logger = logging.getLogger('stoq')
        self._collect_plugins(plugin_dir_list) 
开发者ID:PUNCH-Cyber,项目名称:stoq,代码行数:23,代码来源:plugin_manager.py

示例8: log_enter_exit

# 需要导入模块: import logging [as 别名]
# 或者: from logging import Logger [as 别名]
def log_enter_exit(logger):
    '''Decorator for logger to log function enter and exit.

    This decorator will generate a lot of debug log, please add this
    only when it is required.

    :param logger: Logger to decorate.
    :type logger: ``logging.Logger``

    Usage::
      >>> @log_enter_exit
      >>> def myfunc():
      >>>     doSomething()
    '''

    def log_decorator(func):
        def wrapper(*args, **kwargs):
            logger.debug('%s entered', func.__name__)
            result = func(*args, **kwargs)
            logger.debug('%s exited', func.__name__)
            return result

        return wrapper

    return log_decorator 
开发者ID:remg427,项目名称:misp42splunk,代码行数:27,代码来源:log.py

示例9: setUp

# 需要导入模块: import logging [as 别名]
# 或者: from logging import Logger [as 别名]
def setUp(self):
        self.formatter = LogFormatter(color=False)
        # Fake color support.  We can't guarantee anything about the $TERM
        # variable when the tests are run, so just patch in some values
        # for testing.  (testing with color off fails to expose some potential
        # encoding issues from the control characters)
        self.formatter._colors = {
            logging.ERROR: u("\u0001"),
        }
        self.formatter._normal = u("\u0002")
        # construct a Logger directly to bypass getLogger's caching
        self.logger = logging.Logger('LogFormatterTest')
        self.logger.propagate = False
        self.tempdir = tempfile.mkdtemp()
        self.filename = os.path.join(self.tempdir, 'log.out')
        self.handler = self.make_handler(self.filename)
        self.handler.setFormatter(self.formatter)
        self.logger.addHandler(self.handler) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:20,代码来源:log_test.py

示例10: test_logger

# 需要导入模块: import logging [as 别名]
# 或者: from logging import Logger [as 别名]
def test_logger(self):  # type: () -> ()
        # This test assumes the initial, intended semantics of the various
        # loggers returned. If semantics change, so must the tests.
        init_level = L._root.level
        test_level = 7
        log_name = "TestLoggerLogger"
        log = L.get_logger(log_name)

        with self.subTest(method=L.get_logger):
            self.assertEqual(log.__class__, logging.Logger)
            self.assertEqual(log_name, log.name)
            # Returned loggers should default to 0 (inherit parent level)
            self.assertEqual(0, log.level)

        with self.subTest(method=L.set_level):
            # Assert set_level() sets root level, not sublogger level
            L.set_level(test_level)
            self.assertEqual(test_level, L._root.level)
            self.assertEqual(0, log.level)

            # Restore and verify
            L.set_level(init_level)
            self.assertEqual(init_level, L._root.level)
            self.assertEqual(0, log.level) 
开发者ID:llvm,项目名称:llvm-zorg,代码行数:26,代码来源:test_logger.py

示例11: create_debugging_logger

# 需要导入模块: import logging [as 别名]
# 或者: from logging import Logger [as 别名]
def create_debugging_logger():
    '''
    Creates a debugging logger that prints to console.
    
    :rtype: `logging.Logger` instance
    '''
    global DEFAULT_LOGGER_CREATED

    t_log = logging.getLogger('pySmartDL')

    if not DEFAULT_LOGGER_CREATED:
        t_log.setLevel(logging.DEBUG)
        console = logging.StreamHandler()
        console.setLevel(logging.DEBUG)
        console.setFormatter(logging.Formatter('[%(levelname)s||%(thread)d@{%(pathname)s:%(lineno)d}] %(message)s'))
        t_log.addHandler(console)
        DEFAULT_LOGGER_CREATED = True
    
    return t_log 
开发者ID:iTaybb,项目名称:pySmartDL,代码行数:21,代码来源:utils.py

示例12: get_logger

# 需要导入模块: import logging [as 别名]
# 或者: from logging import Logger [as 别名]
def get_logger(self) -> logging.Logger:
        if self.__logger is None:
            self.__logger = logging.getLogger('code2vec')
            self.__logger.setLevel(logging.INFO)
            self.__logger.handlers = []
            self.__logger.propagate = 0

            formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')

            if self.VERBOSE_MODE >= 1:
                ch = logging.StreamHandler(sys.stdout)
                ch.setLevel(logging.INFO)
                ch.setFormatter(formatter)
                self.__logger.addHandler(ch)

            if self.LOGS_PATH:
                fh = logging.FileHandler(self.LOGS_PATH)
                fh.setLevel(logging.INFO)
                fh.setFormatter(formatter)
                self.__logger.addHandler(fh)

        return self.__logger 
开发者ID:tech-srl,项目名称:code2vec,代码行数:24,代码来源:config.py

示例13: install_environment

# 需要导入模块: import logging [as 别名]
# 或者: from logging import Logger [as 别名]
def install_environment(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger):
    """
    Install the packages mentioned in the model's metadata.

    :param args: :param args: :class:`argparse.Namespace` with "input", "reproduce", "backend", \
                 "args", "username", "password", "remote_repo" and "log_level".
    :param backend: Backend which is responsible for working with model files.
    :param log: Logger supplied by supply_backend
    :return: None
    """
    model = _load_generic_model(args.input, backend, log)
    if model is None:
        return 1
    packages = ["%s==%s" % (pkg, ver) for pkg, ver in model.environment["packages"]]
    cmdline = [sys.executable, "-m", "pip", "install"] + args.pip + packages
    log.info(" ".join(cmdline))
    subprocess.check_call(cmdline)
    if args.reproduce:
        for dataset in model.datasets:
            download_http(dataset[0], dataset[1], log) 
开发者ID:src-d,项目名称:modelforge,代码行数:22,代码来源:tools.py

示例14: initialize_registry

# 需要导入模块: import logging [as 别名]
# 或者: from logging import Logger [as 别名]
def initialize_registry(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger):
    """
    Initialize the registry and the index.

    :param args: :class:`argparse.Namespace` with "backend", "args", "force" and "log_level".
    :param backend: Backend which is responsible for working with model files.
    :param log: Logger supplied by supply_backend
    :return: None
    """
    try:
        backend.reset(args.force)
    except ExistingBackendError:
        return 1

    log.info("Resetting the index ...")
    backend.index.reset()
    try:
        backend.index.upload("reset", {})
    except ValueError:
        return 1
    log.info("Successfully initialized") 
开发者ID:src-d,项目名称:modelforge,代码行数:23,代码来源:registry.py

示例15: delete_model

# 需要导入模块: import logging [as 别名]
# 或者: from logging import Logger [as 别名]
def delete_model(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger):
    """
    Delete a model.

    :param args: :class:`argparse.Namespace` with "input", "backend", "args", "meta", \
                        "update_default", "username", "password", "remote_repo", \
                        "template_model", "template_readme" and "log_level".
    :param backend: Backend which is responsible for working with model files.
    :param log: Logger supplied by supply_backend
    :return: None
    """
    try:
        meta = backend.index.remove_model(args.input)
        template_readme = backend.index.load_template(args.template_readme)
        backend.index.update_readme(template_readme)
    except ValueError:
        return 1
    backend.delete_model(meta)
    log.info("Updating the models index...")
    try:
        backend.index.upload("delete", meta)
    except ValueError:  # TODO: replace with PorcelainError
        return 1
    log.info("Successfully deleted") 
开发者ID:src-d,项目名称:modelforge,代码行数:26,代码来源:registry.py


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