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


Python logger.formatEvent函数代码示例

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


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

示例1: StandardErrorObserver

    def StandardErrorObserver(event):

        if event["log_level"] not in levels:
            return

        if event.get("log_system", "-") == "-":
            logSystem = "{:<10} {:>6}".format("Controller", os.getpid())
        else:
            logSystem = event["log_system"]

        if show_source and event.get("log_source") is not None:
            logSystem += " " + qual(event["log_source"].__class__)

        if format == "colour":
            # Errors are always red, no matter the system they came from.
            eventString = COLOUR_FORMAT.format(
                Fore.RED, formatTime(event["log_time"]), logSystem, Fore.RESET,
                formatEvent(event))
        elif format == "nocolour":
            eventString = NOCOLOUR_FORMAT.format(
                formatTime(event["log_time"]), logSystem, formatEvent(event))
        elif format == "syslogd":
            eventString = SYSLOGD_FORMAT.format(logSystem, formatEvent(event))

        print(eventString, file=_stderr)
开发者ID:terrycojones,项目名称:crossbar,代码行数:25,代码来源:_logging.py

示例2: StandardOutObserver

    def StandardOutObserver(event):

        if event["log_level"] not in levels:
            return

        if event.get("log_system", "-") == "-":
            logSystem = "{:<10} {:>6}".format("Controller", os.getpid())
        else:
            logSystem = event["log_system"]

        if show_source and event.get("log_namespace") is not None:
            logSystem += " " + event.get("cb_namespace", event.get("log_namespace", ''))

        if format == "colour":
            # Choose a colour depending on where the log came from.
            if "Controller" in logSystem:
                fore = Fore.BLUE
            elif "Router" in logSystem:
                fore = Fore.YELLOW
            elif "Container" in logSystem:
                fore = Fore.GREEN
            else:
                fore = Fore.WHITE

            eventString = COLOUR_FORMAT.format(
                fore, formatTime(event["log_time"]), logSystem, Fore.RESET,
                formatEvent(event))
        elif format == "nocolour":
            eventString = NOCOLOUR_FORMAT.format(
                formatTime(event["log_time"]), logSystem, formatEvent(event))
        elif format == "syslogd":
            eventString = SYSLOGD_FORMAT.format(logSystem, formatEvent(event))

        print(eventString, file=_file)
开发者ID:cosmospham,项目名称:crossbar,代码行数:34,代码来源:_logging.py

示例3: StandardOutObserver

    def StandardOutObserver(event):

        if event["log_level"] not in levels:
            return

        if event["log_level"] == LogLevel.debug:
            if event.get("txaio_trace", False) and not trace:
                return

        if event.get("log_system", "-") == "-":
            logSystem = "{:<10} {:>6}".format("Controller", os.getpid())
        else:
            logSystem = event["log_system"]

        if show_source and event.get("log_namespace") is not None:
            logSystem += " " + event.get("cb_namespace", event.get("log_namespace", ''))

        if event.get("log_category"):
            format_string = _categories.get(event['log_category'])
            if format_string:
                event = event.copy()
                event["log_format"] = format_string

        if format == "standard":
            FORMAT_STRING = STANDARD_FORMAT
        elif format == "syslogd":
            FORMAT_STRING = SYSLOGD_FORMAT
        elif format == "none":
            FORMAT_STRING = NONE_FORMAT
        else:
            assert False

        if colour:
            # Choose a colour depending on where the log came from.
            if "Controller" in logSystem:
                fore = Fore.BLUE
            elif "Router" in logSystem:
                fore = Fore.YELLOW
            elif "Container" in logSystem:
                fore = Fore.GREEN
            else:
                fore = Fore.WHITE

            eventString = FORMAT_STRING.format(
                startcolour=fore, time=formatTime(event["log_time"]),
                system=logSystem, endcolour=Fore.RESET,
                text=formatEvent(event))
        else:
            eventString = strip_ansi(FORMAT_STRING.format(
                startcolour=u'', time=formatTime(event["log_time"]),
                system=logSystem, endcolour=u'',
                text=formatEvent(event)))

        print(eventString, file=_file)
开发者ID:RonaldChristopher,项目名称:crossbar,代码行数:54,代码来源:_logging.py

示例4: StandardErrorObserver

    def StandardErrorObserver(event):

        if event["log_level"] not in levels:
            return

        if event.get("log_system", u"-") == u"-":
            logSystem = u"{:<10} {:>6}".format("Controller", os.getpid())
        else:
            logSystem = event["log_system"]

        if show_source and event.get("log_namespace") is not None:
            logSystem += " " + event.get("cb_namespace", event.get("log_namespace", ''))

        if event.get("log_category"):
            format_string = _categories.get(event['log_category'])
            if format_string:
                event = event.copy()
                event["log_format"] = format_string

        if event.get("log_format", None) is not None:
            eventText = formatEvent(event)
        else:
            eventText = u""

        if "log_failure" in event:
            # This is a traceback. Print it.
            eventText = eventText + event["log_failure"].getTraceback()

        if format == "standard":
            FORMAT_STRING = STANDARD_FORMAT
        elif format == "syslogd":
            FORMAT_STRING = SYSLOGD_FORMAT
        elif format == "none":
            FORMAT_STRING = NONE_FORMAT
        else:
            assert False

        if colour:
            # Errors are always red.
            fore = Fore.RED

            eventString = FORMAT_STRING.format(
                startcolour=fore, time=formatTime(event["log_time"]),
                system=logSystem, endcolour=Fore.RESET,
                text=formatEvent(event))
        else:
            eventString = strip_ansi(FORMAT_STRING.format(
                startcolour=u'', time=formatTime(event["log_time"]),
                system=logSystem, endcolour=u'',
                text=formatEvent(event)))

        print(eventString, file=_file)
开发者ID:RonaldChristopher,项目名称:crossbar,代码行数:52,代码来源:_logging.py

示例5: __call__

    def __call__(self, event):
        """
        Write event to syslog.
        """

        # Figure out what the message-text is.
        eventText = formatEvent(event)
        if eventText is None:
            return

        # Figure out what syslog parameters we might need to use.
        level = event.get("log_level", None)
        if level is None:
            if 'log_failure' in event:
                level = LogLevel.critical
            else:
                level = LogLevel.info
        priority = LOGLEVEL_MAP[level]
        facility = int(event.get('log_facility', DEFAULT_FACILITY))

        # Break the message up into lines and send them.
        lines = eventText.split('\n')
        while lines[-1:] == ['']:
            lines.pop()

        firstLine = True
        for line in lines:
            if firstLine:
                firstLine = False
            else:
                line = '        ' + line
            self.syslog(priority | facility,
                        '[%s] %s' % (event.get('log_system', '-'), line))
开发者ID:sveinse,项目名称:lumina,代码行数:33,代码来源:syslog.py

示例6: kafka_observer

def kafka_observer(event):
    message = formatEvent(event)

    event_dict = dict()
    for slot in ['log_logger', 'log_source', 'log_failure']:
        if slot in event:
            event_dict[slot] = repr(event[slot])

    event_dict['log_level'] = event['log_level'].name

    for slot in six.iterkeys(event):
        if slot not in event_dict:
            event_dict[slot] = str(event[slot])

    event_dict['klog_level'] = level_mapping[event_dict['log_level']]
    event_dict['klog_time'] = event_dict['log_time']
    event_dict['klog_message'] = message

    json_dump = json.dumps(event_dict)

    lock.acquire()
    try:
        KafkaLogService.producer.send(str(event['log_namespace']).encode('utf-8') + '.json',
                                      json_dump.encode('utf-8'))
        KafkaLogService.producer.send('all.json', json_dump.encode('utf-8'))

        KafkaLogService.producer.send(str(event['log_namespace']).encode('utf-8') + '.txt',
                                      message.encode('utf-8'))
        KafkaLogService.producer.send('all.txt', message.encode('utf-8'))
        KafkaLogService.producer.flush()
    finally:
        lock.release()
开发者ID:patrickfournier,项目名称:kleverklog,代码行数:32,代码来源:twisted_logger.py

示例7: formatLogEvent

def formatLogEvent(event, formatTime=formatTime):
    eventText = formatEvent(event)
    if not eventText:
        return None

    eventText = eventText.replace(u"\n", u"\n\t")
    timeStamp = formatTime(event.get("log_time", None))

    system = event.get("log_system", None)

    if system is None:
        level = event.get("log_level", None)
        if level is None:
            levelName = u"-"
        else:
            levelName = level.name

        system = u"{namespace}".format(
            namespace=event.get("log_namespace", u"-"),
        )
    else:
        try:
            system = unicode(system)
        except Exception:
            system = u"UNFORMATTABLE"

    return u"{timeStamp} [{system}] {level}: {event}\n".format(
        timeStamp=timeStamp,
        system=system.ljust(35),
        level=levelName.upper().ljust(8),
        event=eventText,
    )
开发者ID:hiveeyes,项目名称:kotori,代码行数:32,代码来源:logger.py

示例8: _render

    def _render(event):

        if event.get("log_system", u"-") == u"-":
            logSystem = u"{:<10} {:>6}".format("Controller", os.getpid())
        else:
            logSystem = event["log_system"]

        if show_source and event.get("log_namespace") is not None:
            logSystem += " " + event.get("cb_namespace", event.get("log_namespace", ''))

        if event.get("log_format", None) is not None:
            eventText = formatEvent(event)
        else:
            eventText = u""

        if "log_failure" in event:
            # This is a traceback. Print it.
            eventText = eventText + event["log_failure"].getTraceback()

        eventString = strip_ansi(STANDARD_FORMAT.format(
            startcolour=u'', time=formatTime(event["log_time"]),
            system=logSystem, endcolour=u'',
            text=eventText)) + os.linesep

        return eventString
开发者ID:RonaldChristopher,项目名称:crossbar,代码行数:25,代码来源:_logging.py

示例9: __call__

    def __call__(self, event):
        # it seems if a twisted.logger.Logger() has .failure() called
        # on it, the log_format will be None for the traceback after
        # "Unhandled error in Deferred" -- perhaps this is a Twisted
        # bug?
        if event['log_format'] is None:
            msg = u'{0} {1}{2}'.format(
                formatTime(event["log_time"]),
                failure_format_traceback(event['log_failure']),
                os.linesep,
            )
            if self._encode:
                msg = msg.encode('utf8')
            self._file.write(msg)
        else:
            # although Logger will already have filtered out unwanted
            # levels, bare Logger instances from Twisted code won't have.
            if 'log_level' in event and self._acceptable_level(event['log_level']):
                msg = u'{0} {1}{2}'.format(
                    formatTime(event["log_time"]),
                    formatEvent(event),
                    os.linesep,
                )
                if self._encode:
                    msg = msg.encode('utf8')

                self._file.write(msg)
开发者ID:Blockshare,项目名称:Django-LandingPage-Template,代码行数:27,代码来源:tx.py

示例10: StandardErrorObserver

    def StandardErrorObserver(event):

        if event["log_level"] not in levels:
            return

        if event.get("log_system", u"-") == u"-":
            logSystem = u"{:<10} {:>6}".format("Controller", os.getpid())
        else:
            logSystem = event["log_system"]

        if show_source and event.get("log_namespace") is not None:
            logSystem += " " + event.get("cb_namespace", event.get("log_namespace", ''))

        if event.get("log_format", None) is not None:
            eventText = formatEvent(event)
        else:
            eventText = ""

        if "log_failure" in event:
            # This is a traceback. Print it.
            eventText = eventText + event["log_failure"].getTraceback()

        if format == "colour":
            # Errors are always red, no matter the system they came from.
            eventString = COLOUR_FORMAT.format(
                Fore.RED, formatTime(event["log_time"]), logSystem, Fore.RESET,
                eventText)
        elif format == "nocolour":
            eventString = NOCOLOUR_FORMAT.format(
                formatTime(event["log_time"]), logSystem, eventText)
        elif format == "syslogd":
            eventString = SYSLOGD_FORMAT.format(logSystem, eventText)

        print(eventString, file=_file)
开发者ID:cosmospham,项目名称:crossbar,代码行数:34,代码来源:_logging.py

示例11: wrapped

    def wrapped(event):
        try:
            # If there is a failure, use the type and message to create the main msg.
            if 'failure' in event:
                f = event['failure']
                parts = [f.type.__name__, f.getErrorMessage()]
                msg = ' '.join(filter(None, parts))

            # Otherwise use normal event formatting to create the main msg.
            else:
                msg = formatEvent(event)

            new = OrderedDict([
                ('level', level_name[event.pop('log_level')]),
                ('msg', msg),
            ])

            if 'log_namespace' in event:
                new['namespace'] = event.pop('log_namespace')

            if 'log_system' in event:
                new['system'] = event.pop('log_system')

            # Keep all keys except the noise.
            for k, v in sorted(event.items()):
                if k not in noisey_keys:
                    new[k] = v

        except Exception as e:
            # Fallback to normal event processing
            new = event
            new['log_failure'] = str(e)

        output.write(new['level'].upper() + ' ')
        json(new)
开发者ID:wrapp,项目名称:txwrapplog,代码行数:35,代码来源:txwrapplog.py

示例12: emit

 def emit(self, event):
     is_error = event.get('isError', False)
     try:
         text = self.format_kv(event)
     except Exception, e:
         text = 'Parse error: %s. Original message: %s' % \
                 (repr(e), formatEvent(event))
         is_error = True
开发者ID:wrapp,项目名称:simple-observers,代码行数:8,代码来源:simple_observers.py

示例13: kafka_observer

def kafka_observer(event):
    message = formatEvent(event)
    event_dict = dict()
    for slot in ['log_logger', 'log_source', 'log_failure']:
        if slot in event:
            event_dict[slot] = repr(event[slot])
    event_dict['log_level'] = event['log_level'].name
    for slot in six.iterkeys(event):
开发者ID:Aoshee,项目名称:klog,代码行数:8,代码来源:twisted_logger.py

示例14: check

 def check(self, **features):
     for key, expected_value in six.iteritems(features):
         if key == 'text':
             text = formatEvent(self.event)
             if text != expected_value:
                 raise AssertionError('Expected log event to look like\n{!r}\nbut was\n{!r}\n{!r}'.format(
                     expected_value, text, self.event))
         else:
             if self.event[key] != expected_value:
                 raise AssertionError('Expected log event to have {!r}: {!r} but was \n{!r}'.format(
                     key, expected_value, self.event))
开发者ID:kpreid,项目名称:shinysdr,代码行数:11,代码来源:testutil.py

示例15: _make_json

    def _make_json(_event):
        event = dict(_event)
        level = event.pop("log_level", LogLevel.info).name

        # as soon as possible, we wish to give up if this event is
        # outside our target log-level; this is to prevent
        # (de-)serializing all the debug() messages (for example) from
        # workers to the controller.
        if log_levels.index(level) > log_levels.index(get_global_log_level()):
            return

        done_json = {
            "level": level,
            "namespace": event.pop("log_namespace", '')
        }

        eventText = formatEvent(event)

        if "log_failure" in event:
            # This is a traceback. Print it.
            traceback = event["log_failure"].getTraceback()

            if not six.PY3:
                traceback = traceback.decode('utf-8')
                linesep = os.linesep.decode('utf-8')
            else:
                linesep = os.linesep

            eventText = eventText + linesep + traceback

        done_json["text"] = escape_formatting(eventText)

        try:
            event.pop("log_logger", "")
            event.pop("log_format", "")
            event.pop("log_source", "")
            event.pop("log_system", "")
            event.pop("log_failure", "")
            event.pop("failure", "")
            event.update(done_json)

            text = encoder.encode(event)

        except Exception:
            text = encoder.encode({
                "text": done_json["text"],
                "level": "error",
                "namespace": "crossbar._logging"})

        if not isinstance(text, six.text_type):
            text = text.decode('utf8')

        print(text, end=record_separator, file=outFile)
        outFile.flush()
开发者ID:RonaldChristopher,项目名称:crossbar,代码行数:54,代码来源:_logging.py


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