How to use the logzero.logger function in logzero

To help you get started, we’ve selected a few logzero examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github openatx / atxserver2-android-provider / heartbeat.py View on Github external
async def _drain_queue(self):
        """
        Logic:
            - send message to server when server is alive
            - update local db
        """
        while True:
            message = await self._queue.get()
            if message is None:
                logger.info("Resent messages: %s", self._db)
                for _, v in self._db.items():
                    await self._ws.write_message(v)
                continue

            if 'udid' in message:  # ping消息不包含在裡面
                udid = message['udid']
                update_recursive(self._db, {udid: message})
            self._queue.task_done()

            if self._ws:
                try:
                    await self._ws.write_message(message)
                    logger.debug("websocket send: %s", message)
                except TypeError as e:
                    logger.info("websocket write_message error: %s", e)
github chaostoolkit-incubator / chaostoolkit-aws / chaosaws / ecs / actions.py View on Github external
if task_percent:
        task_count = int(float(
            len(tasks) * float(task_percent)) / 100)

    if len(tasks) < task_count:
        raise FailedActivity(
            'Not enough running tasks in {} to satisfy '
            'stop count {} ({})'.format(
                cluster, task_count,
                len(tasks)))

    tasks = random.sample(tasks, task_count)

    results = []
    for task in tasks:
        logger.debug("Stopping ECS task: {}".format(task))
        response = client.stop_task(cluster=cluster, task=task, reason=reason)
        results.append({
            'Task_Id': response['task']['taskArn'],
            'Desired_Status': response['task']['desiredStatus']
        })
    return results
github chaostoolkit / chaostoolkit-lib / chaoslib / secret.py View on Github external
def create_vault_client(configuration: Configuration = None):
    """
    Initialize a Vault client from either a token or an approle.
    """
    client = None
    if HAS_HVAC:
        url = configuration.get("vault_addr")
        client = hvac.Client(url=url)

        client.secrets.kv.default_kv_version = str(configuration.get(
            "vault_kv_version", "2"))
        logger.debug(
            "Using Vault secrets KV version {}".format(
                client.secrets.kv.default_kv_version))

        if "vault_token" in configuration:
            client.token = configuration.get("vault_token")
        elif "vault_role_id" in configuration and \
             "vault_role_secret" in configuration:
            role_id = configuration.get("vault_role_id")
            role_secret = configuration.get("vault_role_secret")

            try:
                app_role = client.auth_approle(role_id, role_secret)
            except Exception as ve:
                raise InvalidExperiment(
                    "Failed to connect to Vault with the AppRole: {}".format(
                        str(ve)))
github openatx / atxserver2-ios-provider / heartbeat.py View on Github external
async def connect(self):
        """
        Returns:
            tornado.WebSocketConnection
        """
        cnt = 0
        while True:
            try:
                ws = await self._connect()
                cnt = 0
                return ws
            except Exception as e:
                cnt = min(30, cnt + 1)
                logger.warning("WS connect error: %s, reconnect after %ds", e,
                               cnt + 1)
                await gen.sleep(cnt + 1)
github ansible-community / collection_migration / gh.py View on Github external
async def _get_github_client(self, http_session: ClientSession):
        """Return a GitHub API client for the target org."""
        github_app = self._get_github_app(http_session)
        try:
            github_app_installations = await github_app.get_installations()
        except gidgethub.BadRequest:
            error_msg = 'Invalid GitHub App credentials'
            logger.error(error_msg)
            raise LookupError(error_msg)
        target_github_app_installation = next(  # find the one
            (
                i for n, i in github_app_installations.items()
                if i._metadata.account['login'] == self.github_org_name
            ),
            None,
        )
        return target_github_app_installation.api_client
github openatx / atxserver2-android-provider / core / fetching.py View on Github external
def mirror_download(url: str, target: str) -> str:
    """
    Returns:
        target path
    """
    if os.path.exists(target):
        return target
    github_host = "https://github.com"
    if url.startswith(github_host):
        mirror_url = "http://tool.appetizer.io" + url[len(
            github_host):]  # mirror of github
        try:
            return download(mirror_url, target)
        except (requests.RequestException, ValueError) as e:
            logger.debug("download from mirror error, use origin source")

    return download(url, target)
github ddi-lab / generion-middleware / examples / smart-contract.py View on Github external
def sc_notify(event):
    logger.info("SmartContract Runtime.Notify event: %s", event)

    # Make sure that the event payload list has at least one element.
    if not len(event.event_payload):
        return

    # The event payload list has at least one element. As developer of the smart contract
    # you should know what data-type is in the bytes, and how to decode it. In this example,
    # it's just a string, so we decode it with utf-8:
    logger.info("- payload part 1: %s", event.event_payload[0].decode("utf-8"))
github jctanner / ansible-tools / profiling / makesvg.py View on Github external
thistask = None
    taskcount = 0
    totalrows = len(obs)
    for idr,row in enumerate(obs):
        if row.get('task_name'):
            tn = row.get('task_name')
            ts = row['ts']
            if not thistask or thistask != tn:
                # set the color
                if not _colors:
                    _colors = colors[:]
                taskmap[tn] = _colors[0]
                _colors.remove(_colors[0])
                thistask = tn
                taskcount += 1
                logger.info('[%s] task-%s %s' % (ts, taskcount, tn))

                # find x position
                xp = lpad + ((ts - t0) / tD)

                # label header
                pg = dwg.add(dwg.g(font_size=8, stroke=taskmap[tn]))
                pg.add(dwg.text('task-%s' % taskcount, (pc(xp+.1), pc(tpad-2))))
                # label footer
                pg.add(dwg.text('%s' % round((ts-t0), 4), (pc(xp+.1), pc(100-bpad+2))))

                # divline
                _axiis = dwg.add(dwg.g(id='axiis', stroke=taskmap[tn]))
                _axiis.add(dwg.line(start=(pc(xp),pc(tpad-2)), end=(pc(xp),pc(100-bpad+2))))

    logger.info('%s total tasks' % taskcount)
github chaostoolkit / chaostoolkit-kubernetes / chaosk8s / node / actions.py View on Github external
Nodes can be filtered by their name through the `name` paramteter.
    Nodes can be filtered by their label through the `label_selector`
    parameter.
    Nodes can further be filtered by the pods that they are accommodating using
    the pod's label through the `pod_label_selector` parameter and
    `pod_namespace` parameter.
    The amount of nodes to return can be capped through the `count` paramteter.
    In this case `count` random nodes will be returned.
    If first is set to true only the first node is returned.
    """
    nodes = []
    api = create_k8s_api_client(secrets)
    v1 = client.CoreV1Api(api)

    if name and not label_selector:
        logger.debug("Filtering nodes by name %s" % (name,))
        ret = v1.list_node(field_selector="metadata.name={}".format(name))
        logger.debug("Found {d} nodes".format(d=len(ret.items)))
    elif label_selector and not name:
        logger.debug("Filtering nodes by label %s" % (label_selector,))
        ret = v1.list_node(label_selector=label_selector)
        logger.debug("Found {d} nodes".format(d=len(ret.items)))
    elif name and label_selector:
        logger.debug("Filtering nodes by name %s and \
                      label %s" % (name, label_selector))
        ret = v1.list_node(field_selector="metadata.name={}".format(name),
                           label_selector=label_selector)
        logger.debug("Found {d} nodes".format(d=len(ret.items)))
    else:
        ret = v1.list_node()

    if pod_label_selector and pod_namespace:
github CityOfZion / neo-python / examples / smart-contract-rest-api.py View on Github external
async def custom_background_code():
    """ Custom code run in a background thread. Prints the current block height.

    This function is run in a daemonized thread, which means it can be instantly killed at any
    moment, whenever the main thread quits. If you need more safety, don't use a  daemonized
    thread and handle exiting this thread in another way (eg. with signals and events).
    """
    while True:
        logger.info("Block %s / %s", str(Blockchain.Default().Height), str(Blockchain.Default().HeaderHeight))
        await asyncio.sleep(15)