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


Python logging.Formatter类代码示例

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


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

示例1: __init__

    def __init__(self, stream=None):
        """
        Construct this formatter.

        Provides colored output if the stream parameter is specified and is an acceptable TTY.
        We print hardwired escape sequences, which will probably break in some circumstances;
        for this unfortunate shortcoming, we apologize.
        """

        # select and construct format string
        import curses

        format = None

        if stream and hasattr(stream, "isatty") and stream.isatty():
            curses.setupterm()

            # FIXME do nice block formatting, increasing column sizes as necessary
            if curses.tigetnum("colors") > 2:
                format = "%s%%(asctime)s%s %%(message)s" % (
                    TTY_VerboseFormatter._NAME_COLOR,
                    TTY_VerboseFormatter._COLOR_END,
                )

        if format is None:
            format = "%(name)s - %(levelname)s - %(message)s"

        # initialize this formatter
        Formatter.__init__(self, format, TTY_VerboseFormatter._DATE_FORMAT)
开发者ID:bsilverthorn,项目名称:cargo,代码行数:29,代码来源:log.py

示例2: __init__

    def __init__(self, coloured=False):
        fmt = "%(asctime)s  %(address)s  %(levelname)s: %(message)s"
        datefmt = "%Y-%m-%d %H:%M:%S"
        self.linefmt = "    "
        self._coloured = coloured

        Formatter.__init__(self, fmt, datefmt)
开发者ID:pazdera,项目名称:lnst,代码行数:7,代码来源:Logs.py

示例3: onerror

 def onerror(self, e):
     """Send here Exception and traceback by Error channel
     """
     f = Formatter()
     history = json.dumps(self.channel_history,
                          indent=2,
                          default=datahandler)
     data = (history, xml_escape(f.formatException(sys.exc_info())),)
     if EXCEPTION_FLAVOR == 'html':
         traceback = '<pre>%s\n\n%s</pre>' % data
     else:
         traceback = '%s\n%s' % data
     if DEBUG:
         err_message = {'channel': WS_CHANNELS['ERROR_CHID'],
                        'pkg': {'exception': repr(e), 'tb': traceback}}
     else:
         err_message = {'channel': WS_CHANNELS['ERROR_CHID'],
                        'pkg': {'exception': 'error 500',
                                'tb': 'an error occurred'}}
     log.error(format_exception(e, None), extra=self.channel_history)
     report_exception(e, extra=self.channel_history)
     if not self.ws.closed:
         try:
             self.ws.send(json.dumps(err_message, separators=(', ', ':')))
         except WebSocketError as e:
             if is_ws_error_abnormal(e):
                 log.error('WebSocket fault: %s' % e.message,
                           extra=self.channel_history)
开发者ID:SandStormHoldings,项目名称:NoodlesFramework,代码行数:28,代码来源:apihandler.py

示例4: __init__

 def __init__(self, pidlog=False):
     pidlog = "[%(process)s] " if pidlog else ""
     self._normal_fmt = ("%(asctime)s " + pidlog +
                         "[%(levelname)s %(name)s] %(message)s")
     self._context_fmt = ("%(asctime)s " + pidlog + "[%(levelname)s "
                          "%(name)s] [%(context)s] %(message)s")
     Formatter.__init__(self, self._normal_fmt)
开发者ID:alexanderfefelov,项目名称:nav,代码行数:7,代码来源:log.py

示例5: emit

 def emit(self, record):
     if record.exc_info:
         # The log formatter will use the cached exc_text in place of the
         # exc_info Traceback object; since Traceback objects can't be
         # pickled, use this to pass over the formatted exception text
         # instead.
         fmt = Formatter()
         record.exc_info = fmt.formatException(record.exc_info)
     self.queue.put(record)
开发者ID:dchangtw,项目名称:flent,代码行数:9,代码来源:loggers.py

示例6: __init__

 def __init__(self,recordfields = [], datefmt=None, customjson=None):
     """__init__ overrides the default constructor to accept a formatter specific list of metadata fields 
     
     Args:
         recordfields : A list of strings referring to metadata fields on the record object. It can be empty.
                        The list of fields will be added to the JSON record created by the formatter. 
     """
     Formatter.__init__(self,None,datefmt)
     self.recordfields = recordfields
     self.customjson   = customjson
开发者ID:NyproTheGeek,项目名称:Managed-Files,代码行数:10,代码来源:recipe-580667.py

示例7: __init__

    def __init__(self, prefix='', only_from=None):
        """
        .. todo::

            WRITEME
        """
        Formatter.__init__(self)
        self._info_fmt = prefix + "%(message)s"
        self._fmt = prefix + "%(levelname)s (%(name)s): %(message)s"
        self._only_from = only_from
开发者ID:JakeMick,项目名称:pylearn2,代码行数:10,代码来源:logger.py

示例8: __init__

 def __init__(self, formatter_for_level=dict(), default=Formatter()):
     """
     Use the given formatter_for_level map of {level: formatter} to
     format messages. If for a given level, a formatter does not exist in
     the formatter_for_level dictionary, the default formatter specified
     by 'default' is used instead.
     """
     Formatter.__init__(self)
     self.formatter_for_level = formatter_for_level
     self.default = default
开发者ID:AdrienDebrie,项目名称:sequencer,代码行数:10,代码来源:tracer.py

示例9: __init__

    def __init__(self, stream, *args, **kwds):
        Formatter.__init__(self, *args, **kwds)

        # Create a mapping of levels to format string which is prepared to
        # contain the escape sequences.
        term = TerminalController(stream)
        self.color_fmt = {}
        for levelno, colstr in self.colordef:
            slist = [getattr(term, c) for c in colstr.split()] + ['%s', term.NORMAL]
            self.color_fmt[levelno] = ''.join(slist)
开发者ID:merriam,项目名称:beancount,代码行数:10,代码来源:colorlog.py

示例10: noodlesapp

def noodlesapp(env, start_response):
    """

    :rtype : noodles.http.Response
    :param env:
    :param start_response:
    :return: :rtype: :raise:
    """
    # Get request object
    if get_config('ENCODE_SEMICOLON_IN_REQUEST') is True:
        env['QUERY_STRING'] = re.sub('[;]', '%3b', env['QUERY_STRING'])
    request = Request(env)

    if "HTTP_X_FORWARDED_FOR" in env:
        x_forwarded_for = env["HTTP_X_FORWARDED_FOR"].split(',')[:1]
        if x_forwarded_for:
            request.remote_addr = x_forwarded_for[0]
    #print("Try to handle url_path '%s'" % request.path)
    # Get callable object with routine method to handle request
    producer = dispatcher.get_callable(request)
    if not producer:
        # May be here an error,raise exception
        raise Exception('Can\'t find callable for this url path')

    # Callable function must return Response object
    try:
        response = middlewares.run_chain(producer, request)
        if not hasattr(response, 'is_noodles_response'):
            response = producer()
    # Capture traceback here and send it if debug mode
    except Exception as e:
        f = Formatter()
        if EXCEPTION_FLAVOR=='html':
            traceback = '<pre>%s\n\n%s</pre>' \
                        % (json.dumps(env, indent=2, default=datahandler),
                           xml_escape(f.formatException(sys.exc_info())))
        else:
            traceback = '%s\n%s' \
                        % (json.dumps(env, indent=2, default=datahandler),
                           f.formatException(sys.exc_info()))
        extra = {'request': request}
        log.error(format_exception(e, None), extra=extra)
        report_exception(e, extra=extra)

        if DEBUG:
            response = Error500(e, traceback)
        else:
            response = Error500()
    finally:
        middlewares.end_chain(lambda x: x, request)

    return response(env, start_response)
开发者ID:SandStormHoldings,项目名称:NoodlesFramework,代码行数:52,代码来源:app.py

示例11: format

    def format (self, record):
        # Add the color codes to the record
        record.__dict__.update(escape_codes)

        # If we recognise the level name,
        # add the levels color as `log_color`
        if record.levelname in self.log_colors:
            color = self.log_colors[record.levelname]
            record.log_color = escape_codes[color]
        else:
            record.log_color = ""

        #NOTE: caller_name is very slow
        #record.__dict__['caller_name'] = caller_name(9)
        record.__dict__['abbr_levelname'] = record.levelname[0]
        record.__dict__['pathname2'] = '.'.join(record.pathname.split('/')[-2:]).rstrip('.py')

        # Format the message
        if version_info > (2, 7):
            message = super(ColoredFormatter, self).format(record)
        else:
            message = Formatter.format(self, record)

        # Add a reset code to the end of the message (if it wasn't explicitly added in format str)
        if self.reset and not message.endswith(escape_codes['reset']):
            message += escape_codes['reset']

        return message
开发者ID:justinleoye,项目名称:crawler-group,代码行数:28,代码来源:log_utils.py

示例12: format

 def format(self, record):
     record = deepcopy(record)
     if self.usesColor:
         color_end = '\033[00m'
         try:
             color_begin= {
                  logging.DEBUG    : '',
                  logging.INFO     : '\033[01;32m',
                  logging.WARNING  : '\033[01;33m',
                  logging.ERROR    : '\033[01;31m',
                  logging.CRITICAL : '\033[01;31m',
                  logging.FATAL    : '\033[00;31m'
                 }[record.levelno]
         except:
             color_begin = ''
             color_end = ''
             
         record.levelname = color_begin+'*'+color_end
         
         #record.levelno == logging.ERROR or 
         if record.levelno == logging.CRITICAL or record.levelno == logging.FATAL:
             record.msg = color_begin+record.msg+color_end
     if self.useIdents:
         ident = len(inspect.stack())
         if ident<self.minIdent:
             self.minIdent = ident
         record.msg=' '*(ident-self.minIdent)+record.msg
     return Formatter.format(self, record)
开发者ID:wdanilo,项目名称:dotfiles,代码行数:28,代码来源:colorFormatter.py

示例13: __init__

 def __init__(self, tag=None, withpid=False, **kwargs):
     super(SysLogHandler, self).__init__(**kwargs)
     # 产生tag的formatter
     fmt = tag or "%(name)s"
     if withpid:
         fmt += "[%(process)d]"
     self.tag_formatter = Formatter(fmt)
开发者ID:graycarl,项目名称:moon,代码行数:7,代码来源:logging.py

示例14: format

    def format(self, record):
        try:
            msg = super(ANSIFormatter, self).format(record)
        except:
            # for python2.6
            # Formatter is old-style class in python2.6 and type is classobj
            # another trick: http://stackoverflow.com/a/18392639/1276501
            msg = Formatter.format(self, record)

        lvl2color = {
            "DEBUG": "blue",
            "INFO": "green",
            "WARNING": "yellow",
            "ERROR": "red",
            "CRITICAL": "bgred"
        }

        rln = record.levelname
        if rln in lvl2color:
            return "[{0}]: {1}".format(
                utils.color_msg(lvl2color[rln], rln),
                msg
            )
        else:
            return msg
开发者ID:the7day,项目名称:simiki,代码行数:25,代码来源:log.py

示例15: format

    def format(self, record):
        if not getattr(record, 'session', None):
            record.session =  ''
            record.sessionLS = ' %s' % record.session
            record.sessionRS = '%s ' % record.session
        else:
            record.sessionLS = ' %s' % record.session
            record.sessionRS = '%s ' % record.session

        if not getattr(record, 'classname', None):
            record.classname = ''
        if not getattr(record, 'method', None):
            record.method = record.funcName
        if not getattr(record, 'classAndmethod', None):
            if record.method and record.classname:
                record.classAndMethod = '%s::%s' % (record.classname, record.method)
            else:
                record.classAndMethod = ''

        created = localtime(record.created)
        record.date = strftime('%Y-%m-%d', created)
        record.time = strftime('%H:%M:%S', created)
        record.asctimeshort = '%s %s' % (record.date, record.time)

        #return Formatter.format(self, record)

        ## splits the record and formats every line
        msg = record.getMessage()
        res = []
        for line in msg.split("\n"):
            record.msg, record.args = line, None
            res.append(Formatter.format(self, record))
        return "\n".join(res)
开发者ID:native2k,项目名称:dockstarTouchIf,代码行数:33,代码来源:Logging.py


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