• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python txaio.make_logger函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中txaio.make_logger函数的典型用法代码示例。如果您正苦于以下问题:Python make_logger函数的具体用法?Python make_logger怎么用?Python make_logger使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: _run_command_keys

def _run_command_keys(options, reactor, personality):
    """
    Subcommand "crossbar keys".
    """
    log = make_logger()

    from crossbar.common.key import _read_node_key
    from crossbar.common.key import _read_release_key

    if options.generate:
        # Generate a new node key pair (2 files), load and check
        _maybe_generate_key(options.cbdir)
    else:
        # Print keys

        # Release (public) key
        release_pubkey = _read_release_key()

        # Node key
        node_key = _read_node_key(options.cbdir, private=options.private)

        if options.private:
            key_title = 'Crossbar.io Node PRIVATE Key'
        else:
            key_title = 'Crossbar.io Node PUBLIC Key'

        log.info('')
        log.info('{key_title}', key_title=hl('Crossbar Software Release Key', color='yellow', bold=True))
        log.info('base64: {release_pubkey}', release_pubkey=release_pubkey[u'base64'])
        log.info(release_pubkey[u'qrcode'].strip())
        log.info('')
        log.info('{key_title}', key_title=hl(key_title, color='yellow', bold=True))
        log.info('hex: {node_key}', node_key=node_key[u'hex'])
        log.info(node_key[u'qrcode'].strip())
        log.info('')
开发者ID:goeddea,项目名称:crossbar,代码行数:35,代码来源:main.py


示例2: test_start_router_component_invalid_type

    def test_start_router_component_invalid_type(self):
        """
        Trying to start a component with an invalid type fails.
        """
        log_list = []

        r = router.RouterWorkerSession(config=self.config, reactor=reactor)
        r.log = make_logger(observer=log_list.append, log_level="debug")

        # Open the transport
        transport = FakeWAMPTransport(r)
        r.onOpen(transport)

        realm_config = {
            u"name": u"realm1",
            u'roles': []
        }

        r.start_router_realm(u"realm1", realm_config)

        component_config = {
            u"type": u"notathingcrossbarsupports",
            u"realm": u"realm1"
        }

        with self.assertRaises(ApplicationError) as e:
            r.start_router_component("newcomponent", component_config)

        self.assertEqual(e.exception.error, u"crossbar.error.invalid_configuration")

        self.assertEqual(len(r.get_router_components()), 0)
开发者ID:FirefighterBlu3,项目名称:crossbar,代码行数:31,代码来源:test_router.py


示例3: __init__

    def __init__(self, options, session, auth_config=None):
        """
        Ctor.

        :param options: Options for path service from configuration.
        :type options: dict
        :param session: Instance of `ApplicationSession` to be used for forwarding events.
        :type session: obj
        """
        Resource.__init__(self)
        self._options = options
        self._session = session
        self.log = make_logger()

        self._key = None
        if 'key' in options:
            self._key = options['key'].encode('utf8')

        self._secret = None
        if 'secret' in options:
            self._secret = options['secret'].encode('utf8')

        self._post_body_limit = int(options.get('post_body_limit', 0))
        self._timestamp_delta_limit = int(options.get('timestamp_delta_limit', 300))

        self._require_ip = None
        if 'require_ip' in options:
            self._require_ip = [ip_network(net) for net in options['require_ip']]

        self._require_tls = options.get('require_tls', None)

        self._auth_config = auth_config or {}
        self._pending_auth = None
开发者ID:goeddea,项目名称:crossbar,代码行数:33,代码来源:common.py


示例4: _run_command_init

def _run_command_init(options, reactor, personality):
    """
    Subcommand "crossbar init".
    """
    log = make_logger()

    if options.appdir is None:
        options.appdir = '.'

    options.appdir = os.path.abspath(options.appdir)
    cbdir = os.path.join(options.appdir, '.crossbar')

    if os.path.exists(options.appdir):
        log.warn("Application directory '{appdir}' already exists!", appdir=options.appdir)
    else:
        try:
            os.mkdir(options.appdir)
        except Exception as e:
            raise Exception("could not create application directory '{}' ({})".format(options.appdir, e))
        else:
            log.info("Crossbar.io application directory '{appdir}' created", appdir=options.appdir)

    log.info("Initializing application directory '{options.appdir}' ..", options=options)

    get_started_hint = Templates.init(options.appdir, template='default')

    _maybe_generate_key(cbdir)

    log.info("Application directory initialized")

    if get_started_hint:
        log.info("\n{hint}\n", hint=get_started_hint)
    else:
        log.info("\nTo start your node, run 'crossbar start --cbdir {cbdir}'\n",
                 cbdir=os.path.abspath(cbdir))
开发者ID:crossbario,项目名称:crossbar,代码行数:35,代码来源:main.py


示例5: _appsession_loader

def _appsession_loader(config):
    """
    Load a class or a WAMPlet from C{config}.
    """
    log = make_logger()

    if config['type'] == 'class':

        try:
            klassname = config['classname']

            log.debug("Starting class '{klass}'", klass=klassname)

            c = klassname.split('.')
            module_name, klass_name = '.'.join(c[:-1]), c[-1]
            module = importlib.import_module(module_name)
            component = getattr(module, klass_name)

            if not issubclass(component, ApplicationSession):
                raise ApplicationError(
                    u"crossbar.error.class_import_failed", "session not derived of ApplicationSession"
                )

        except Exception:
            emsg = "Failed to import class '{}'\n{}".format(
                klassname, Failure().getTraceback())
            log.debug(emsg)
            log.debug("PYTHONPATH: {pythonpath}", pythonpath=sys.path)
            raise ApplicationError(
                u"crossbar.error.class_import_failed",
                emsg,
                pythonpath=sys.path
            )

    elif config['type'] == 'wamplet':

        try:
            dist = config['package']
            name = config['entrypoint']

            log.debug("Starting WAMPlet '{dist}/{name}'", dist=dist, name=name)

            # component is supposed to make instances of ApplicationSession
            component = pkg_resources.load_entry_point(
                dist, 'autobahn.twisted.wamplet', name)

        except Exception:
            emsg = "Failed to import wamplet '{}/{}'\n{}".format(
                dist, name, Failure().getTraceback())
            log.error(emsg)
            raise ApplicationError(u"crossbar.error.class_import_failed", emsg)

    else:
        raise ApplicationError(
            u"crossbar.error.invalid_configuration",
            "invalid component type '{}'".format(config['type'])
        )

    return component
开发者ID:schoonc,项目名称:crossbar,代码行数:59,代码来源:__init__.py


示例6: run

def run(components, log_level='info'):
    """
    High-level API to run a series of components.

    This will only return once all the components have stopped
    (including, possibly, after all re-connections have failed if you
    have re-connections enabled). Under the hood, this calls

    XXX fixme for asyncio

    -- if you wish to manage the loop loop yourself, use the
    :meth:`autobahn.asyncio.component.Component.start` method to start
    each component yourself.

    :param components: the Component(s) you wish to run
    :type components: Component or list of Components

    :param log_level: a valid log-level (or None to avoid calling start_logging)
    :type log_level: string
    """

    # actually, should we even let people "not start" the logging? I'm
    # not sure that's wise... (double-check: if they already called
    # txaio.start_logging() what happens if we call it again?)
    if log_level is not None:
        txaio.start_logging(level=log_level)
    loop = asyncio.get_event_loop()
    log = txaio.make_logger()

    # see https://github.com/python/asyncio/issues/341 asyncio has
    # "odd" handling of KeyboardInterrupt when using Tasks (as
    # run_until_complete does). Another option is to just resture
    # default SIGINT handling, which is to exit:
    #   import signal
    #   signal.signal(signal.SIGINT, signal.SIG_DFL)

    @asyncio.coroutine
    def exit():
        return loop.stop()

    def nicely_exit(signal):
        log.info("Shutting down due to {signal}", signal=signal)
        for task in asyncio.Task.all_tasks():
            task.cancel()
        asyncio.ensure_future(exit())

    loop.add_signal_handler(signal.SIGINT, partial(nicely_exit, 'SIGINT'))
    loop.add_signal_handler(signal.SIGTERM, partial(nicely_exit, 'SIGTERM'))

    # returns a future; could run_until_complete() but see below
    component._run(loop, components)

    try:
        loop.run_forever()
        # this is probably more-correct, but then you always get
        # "Event loop stopped before Future completed":
        # loop.run_until_complete(f)
    except asyncio.CancelledError:
        pass
开发者ID:Anggi-Permana-Harianja,项目名称:autobahn-python,代码行数:59,代码来源:component.py


示例7: log_started

def log_started(framework):
    """
    Sets up the logging, which we can only do once per run.
    """
    early_log = txaio.make_logger()
    early_log.info("early log")

    txaio.start_logging(out=_handler, level='debug')
开发者ID:oberstet,项目名称:txaio,代码行数:8,代码来源:test_logging.py


示例8: test_log_noop_trace

def test_log_noop_trace(handler, framework):
    # trace should be a no-op, because we set the level to 'debug' in
    # the fixture
    logger = txaio.make_logger()

    logger.trace("a trace message")

    assert len(handler.messages) == 0
开发者ID:koobs,项目名称:txaio,代码行数:8,代码来源:test_logging.py


示例9: test_set_global_changes_loggers

 def test_set_global_changes_loggers(self):
     """
     Setting the global log level changes the level of all loggers that were
     not instantiated with a level.
     """
     log = make_logger()
     self.assertEqual(log._log_level, "info")
     set_global_log_level("warn")
     self.assertEqual(log._log_level, "warn")
开发者ID:FirefighterBlu3,项目名称:crossbar,代码行数:9,代码来源:test_logger.py


示例10: test_set_global_does_not_change_explicit_loggers

 def test_set_global_does_not_change_explicit_loggers(self):
     """
     Setting the global log level does not change loggers that have an
     explicit level set.
     """
     log = make_logger("info")
     self.assertEqual(log._log_level, "info")
     set_global_log_level("warn")
     self.assertEqual(log._log_level, "info")
开发者ID:FirefighterBlu3,项目名称:crossbar,代码行数:9,代码来源:test_logger.py


示例11: test_basic

    def test_basic(self):

        stream = NativeStringIO()
        observer = make_stderr_observer(_file=stream)
        log = make_logger(observer=observer)

        log.error("Hi!", log_system="foo")

        result = stream.getvalue()
        self.assertIn(u"[foo]", result)
开发者ID:FirefighterBlu3,项目名称:crossbar,代码行数:10,代码来源:test_logger.py


示例12: log_started

def log_started():
    """
    Sets up the logging, which we can only do once per run.
    """
    early_log = txaio.make_logger()
    early_log.info("early log")

    handler = TestHandler()
    txaio.start_logging(out=handler, level='debug')
    return handler
开发者ID:hlamer,项目名称:txaio,代码行数:10,代码来源:test_logging.py


示例13: test_logger_failure

    def test_logger_failure(self):
        """
        The failure method catches the in-flight exception.
        """
        log = make_logger("info", logger=Mock)

        try:
            1 / 0
        except:
            log.failure("Failure happened!")

        self.assertEqual(log._logger.failure.call_count, 1)
开发者ID:FirefighterBlu3,项目名称:crossbar,代码行数:12,代码来源:test_logger.py


示例14: test_critical

def test_critical(handler):
    logger = txaio.make_logger()

    # do something a little fancy, with attribute access etc.
    logger.critical(
        "{adjective} {nouns[2]}",
        adjective='hilarious',
        nouns=['skunk', 'elephant', 'wombat'],
    )

    assert len(handler.messages) == 1
    assert handler.messages[0].endswith(b"hilarious wombat")
开发者ID:hlamer,项目名称:txaio,代码行数:12,代码来源:test_logging.py


示例15: test_logger_failure_not_called

    def test_logger_failure_not_called(self):
        """
        The failure method isn't called under 'none'.
        """
        log = make_logger("none", logger=Mock)

        try:
            1 / 0
        except:
            log.failure("Failure happened!")

        self.assertEqual(log._logger.failure.call_count, 0)
开发者ID:FirefighterBlu3,项目名称:crossbar,代码行数:12,代码来源:test_logger.py


示例16: test_info

def test_info(handler, framework):
    logger = txaio.make_logger()

    # do something a little fancy, with attribute access etc.
    logger.info(
        "{adjective} {nouns[1]}",
        adjective='hilarious',
        nouns=['skunk', 'elephant', 'wombat'],
    )

    assert len(handler.messages) == 1
    assert handler.messages[0].endswith(b"hilarious elephant")
开发者ID:koobs,项目名称:txaio,代码行数:12,代码来源:test_logging.py


示例17: test_capturer

    def test_capturer(self):
        """
        The log capturer is a context manager that captures the logs emitted
        inside it.
        """
        log = make_logger("info")

        with LogCapturer() as l:
            log.info("Whee!", log_category="CB500", foo="bar")

        self.assertEqual(len(l.get_category("CB500")), 1)
        self.assertEqual(l.get_category("CB500")[0]["foo"], "bar")
开发者ID:FirefighterBlu3,项目名称:crossbar,代码行数:12,代码来源:test_logger.py


示例18: __init__

    def __init__(self, controller, id, who, keeplog=None):
        """
        Ctor.

        :param controller: The node controller this worker was created by.
        :type controller: instance of NodeController
        :param id: The ID of the worker.
        :type id: str
        :param who: Who triggered creation of this worker.
        :type who: str
        :param keeplog: If not `None`, buffer log message received to be later
                        retrieved via getlog(). If `0`, keep infinite log internally.
                        If `> 0`, keep at most such many log entries in buffer.
        :type keeplog: int or None
        """
        self._logger = make_logger()

        self._controller = controller

        self.id = id
        self.who = who
        self.pid = None
        self.status = u'starting'

        self.created = datetime.utcnow()
        self.connected = None
        self.started = None

        self.proto = None
        self.pinfo = None

        self._log_entries = deque(maxlen=10)

        if platform.isWindows():
            self._log_fds = [2]
        else:
            self._log_fds = [1, 2]
        self._log_lineno = 0
        self._log_topic = u'crossbar.worker.{}.on_log'.format(self.id)

        self._log_rich = None  # Does not support rich logs

        # track stats for worker->controller traffic
        self._stats = {}
        self._stats_printer = None

        # A deferred that resolves when the worker is ready.
        self.ready = Deferred()

        # A deferred that resolves when the worker has exited.
        self.exit = Deferred()
        self.exit.addBoth(self._dump_remaining_log)
开发者ID:goeddea,项目名称:crossbar,代码行数:52,代码来源:worker.py


示例19: install_reactor

def install_reactor(explicit_reactor=None, verbose=False, log=None, require_optimal_reactor=True):
    """
    Install Twisted reactor.

    :param explicit_reactor: If provided, install this reactor. Else, install
        the optimal reactor.
    :type explicit_reactor: obj

    :param verbose: If ``True``, log (at level "info") the reactor that is
        in place afterwards.
    :type verbose: bool

    :param log: Explicit logging to this txaio logger object.
    :type log: obj

    :param require_optimal_reactor: If ``True`` and the desired reactor could not be installed,
        raise ``ReactorAlreadyInstalledError``, else fallback to another reactor.
    :type require_optimal_reactor: bool

    :returns: The Twisted reactor in place (`twisted.internet.reactor`).
    """
    if not log:
        log = txaio.make_logger()

    if explicit_reactor:
        # install explicitly given reactor
        #
        from twisted.application.reactors import installReactor
        if verbose:
            log.info('Trying to install explicitly specified Twisted reactor "{reactor}" ..', reactor=explicit_reactor)
        try:
            installReactor(explicit_reactor)
        except:
            log.failure('Could not install Twisted reactor {reactor}\n{log_failure.value}',
                        reactor=explicit_reactor)
            sys.exit(1)
    else:
        # automatically choose optimal reactor
        #
        if verbose:
            log.info('Automatically choosing optimal Twisted reactor ..')
        install_optimal_reactor(require_optimal_reactor)

    # now the reactor is installed, import it
    from twisted.internet import reactor
    txaio.config.loop = reactor

    if verbose:
        from twisted.python.reflect import qual
        log.info('Running on Twisted reactor {reactor}', reactor=qual(reactor.__class__))

    return reactor
开发者ID:crossbario,项目名称:autobahn-python,代码行数:52,代码来源:choosereactor.py


示例20: test_emit_noop

def test_emit_noop(handler, framework):
    """
    emit() with a too-low level is an no-op.
    """
    logger = txaio.make_logger()

    old_log = txaio.get_global_log_level()
    txaio.set_global_log_level("info")

    logger.emit("debug", "foobar")

    txaio.set_global_log_level(old_log)

    assert len(handler.messages) == 0
开发者ID:oberstet,项目名称:txaio,代码行数:14,代码来源:test_logging.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python txaio.reject函数代码示例发布时间:2022-05-27
下一篇:
Python txaio.create_future函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap