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


Python logging.makeLogRecord方法代码示例

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


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

示例1: test_multiline_formatter_puts_message_lines_into_data_area

# 需要导入模块: import logging [as 别名]
# 或者: from logging import makeLogRecord [as 别名]
def test_multiline_formatter_puts_message_lines_into_data_area():
    """
    We want logs to look like:

    01 19:36:09.823  |This is
                     |multiline
                     |content
    """
    from moler.config.loggers import MultilineWithDirectionFormatter

    formatter = MultilineWithDirectionFormatter(fmt="%(asctime)s.%(msecs)03d |%(message)s", datefmt="%d %H:%M:%S")
    tm_struct = time.strptime("2000-01-01 19:36:09", "%Y-%m-%d %H:%M:%S")
    epoch_tm = time.mktime(tm_struct)
    logging_time = epoch_tm
    log_rec = logging.makeLogRecord({'msg': "This is\nmultiline\ncontent",
                                     'created': logging_time, 'msecs': 823})
    output = formatter.format(log_rec)

    assert output == "01 19:36:09.823 |This is\n" \
                     "                |multiline\n" \
                     "                |content" 
开发者ID:nokia,项目名称:moler,代码行数:23,代码来源:test_loggers.py

示例2: handle_log

# 需要导入模块: import logging [as 别名]
# 或者: from logging import makeLogRecord [as 别名]
def handle_log(self, obj):
        """Handle an incoming log processing request.

        :param obj: The Channels message object. Command object format:

            .. code-block:: none

                {
                    'command': 'log',
                    'message': [log message]
                }
        """
        record_dict = json.loads(obj[ExecutorProtocol.LOG_MESSAGE])
        record_dict["msg"] = record_dict["msg"]

        executors_dir = os.path.join(
            os.path.dirname(os.path.dirname(__file__)), "executors"
        )
        record_dict["pathname"] = os.path.join(executors_dir, record_dict["pathname"])

        logger.handle(logging.makeLogRecord(record_dict)) 
开发者ID:genialis,项目名称:resolwe,代码行数:23,代码来源:listener.py

示例3: __init__

# 需要导入模块: import logging [as 别名]
# 或者: from logging import makeLogRecord [as 别名]
def __init__(self, fmt=None, datefmt=None):
        """Initialization method.

        Args:
            fmt (string): Log message format.

            datefmt (dict): Log date format.

        Returns:
            New instance of :class:`StructuredFormatter`

        Examples:
            >>> StructuredFormatter("%(message)s")  # doctest: +ELLIPSIS
            <pygogo.formatters.StructuredFormatter object at 0x...>
        """
        empty_record = logging.makeLogRecord({})
        filterer = lambda k: k not in empty_record.__dict__ and k != "asctime"
        self.filterer = filterer
        super(StructuredFormatter, self).__init__(fmt, datefmt) 
开发者ID:reubano,项目名称:pygogo,代码行数:21,代码来源:formatters.py

示例4: filter

# 需要导入模块: import logging [as 别名]
# 或者: from logging import makeLogRecord [as 别名]
def filter(self, record):
        """Determines whether or a not a message should be logged.

        Args:
            record (obj): The event to (potentially) log

        Returns:
            bool: True if the event level is lower than self.high_level

        Examples:
            >>> attrs = {'levelno': logging.INFO}
            >>> record = logging.makeLogRecord(attrs)
            >>> LogFilter(40).filter(record)
            True
        """
        return record.levelno < self.high_level 
开发者ID:reubano,项目名称:pygogo,代码行数:18,代码来源:utils.py

示例5: test_file_filter

# 需要导入模块: import logging [as 别名]
# 或者: from logging import makeLogRecord [as 别名]
def test_file_filter():
    ffilter = FileFilter('pyppl', ['INFO'])
    record = logging.makeLogRecord(
        dict(
            msg="This is logging record1.",
            mylevel="INFO",
            ispbar=False,
        ))
    assert not ffilter.filter(record)

    record = logging.makeLogRecord(
        dict(
            msg="This is logging record1.",
            formatted="This is logging record1.",
            mylevel="INFO",
            ispbar=False,
        ))
    assert ffilter.filter(record) 
开发者ID:pwwang,项目名称:PyPPL,代码行数:20,代码来源:test_logger.py

示例6: test_file_formatter

# 需要导入模块: import logging [as 别名]
# 或者: from logging import makeLogRecord [as 别名]
def test_file_formatter():
    ffmt = FileFormatter()
    record = logging.makeLogRecord(
        dict(
            msg="This is logging record1.",
            #formatted = "\x1b[31mThis is logging record2.\x1b[0m",
            mylevel="INFO",
            ispbar=False,
        ))
    assert 'This is logging record1.' in ffmt.format(record)

    record = logging.makeLogRecord(
        dict(
            msg="This is logging record1.",
            formatted="\x1b[31mThis is logging record2.\x1b[0m",
            mylevel="INFO",
            ispbar=False,
        ))
    assert ffmt.format(record) == 'This is logging record2.' 
开发者ID:pwwang,项目名称:PyPPL,代码行数:21,代码来源:test_logger.py

示例7: test_error_handling

# 需要导入模块: import logging [as 别名]
# 或者: from logging import makeLogRecord [as 别名]
def test_error_handling(self):
        h = TestStreamHandler(BadStream())
        r = logging.makeLogRecord({})
        old_raise = logging.raiseExceptions

        try:
            h.handle(r)
            self.assertIs(h.error_record, r)

            h = logging.StreamHandler(BadStream())
            with support.captured_stderr() as stderr:
                h.handle(r)
                msg = '\nRuntimeError: deliberate mistake\n'
                self.assertIn(msg, stderr.getvalue())

            logging.raiseExceptions = False
            with support.captured_stderr() as stderr:
                h.handle(r)
                self.assertEqual('', stderr.getvalue())
        finally:
            logging.raiseExceptions = old_raise

# -- The following section could be moved into a server_helper.py module
# -- if it proves to be of wider utility than just test_logging 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:26,代码来源:test_logging.py

示例8: test_basic

# 需要导入模块: import logging [as 别名]
# 或者: from logging import makeLogRecord [as 别名]
def test_basic(self):
        sockmap = {}
        server = TestSMTPServer((support.HOST, 0), self.process_message, 0.001,
                                sockmap)
        server.start()
        addr = (support.HOST, server.port)
        h = logging.handlers.SMTPHandler(addr, 'me', 'you', 'Log',
                                         timeout=self.TIMEOUT)
        self.assertEqual(h.toaddrs, ['you'])
        self.messages = []
        r = logging.makeLogRecord({'msg': 'Hello \u2713'})
        self.handled = threading.Event()
        h.handle(r)
        self.handled.wait(self.TIMEOUT)  # 14314: don't wait forever
        server.stop()
        self.assertTrue(self.handled.is_set())
        self.assertEqual(len(self.messages), 1)
        peer, mailfrom, rcpttos, data = self.messages[0]
        self.assertEqual(mailfrom, 'me')
        self.assertEqual(rcpttos, ['you'])
        self.assertIn('\nSubject: Log\n', data)
        self.assertTrue(data.endswith('\n\nHello \u2713'))
        h.close() 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:25,代码来源:test_logging.py

示例9: _heartbeat

# 需要导入模块: import logging [as 别名]
# 或者: from logging import makeLogRecord [as 别名]
def _heartbeat(self) -> None:
        if not self.heartbeatInterval:
            return

        # check if `heartbeatInterval` seconds have passed.
        # if they have, emit a heartbeat log record to the target handler
        _now = time.monotonic()
        _diff = _now - self._s_time
        if _diff >= self.heartbeatInterval:
            self._s_time = _now
            # see: https://docs.python.org/3/library/logging.html#logging.LogRecord
            record = logging.makeLogRecord(
                {
                    "level": logging.INFO,
                    "name": "BreachHandler",
                    "pathname": ".../naz/naz/log.py",
                    "func": "BreachHandler._heartbeat",
                    "msg": {
                        "event": "naz.BreachHandler.heartbeat",
                        "heartbeatInterval": self.heartbeatInterval,
                    },
                }
            )
            self.target.emit(record=record)  # type: ignore # pytype: disable=attribute-error 
开发者ID:komuw,项目名称:naz,代码行数:26,代码来源:log.py

示例10: test_multiline_formatter

# 需要导入模块: import logging [as 别名]
# 或者: from logging import makeLogRecord [as 别名]
def test_multiline_formatter():
    import logging
    from ldap2pg.config import MultilineFormatter

    formatter = MultilineFormatter("prefix: %(message)s")

    base_record = dict(
        name='pouet', level=logging.DEBUG, fn="(unknown file)", lno=0, args=(),
        exc_info=None,
    )
    record = logging.makeLogRecord(dict(base_record, msg="single line"))
    payload = formatter.format(record)
    assert "prefix: single line" == payload

    record = logging.makeLogRecord(dict(base_record, msg="Uno\nDos\nTres"))

    payload = formatter.format(record)
    wanted = dedent("""\
    prefix: Uno
    prefix: Dos
    prefix: Tres
    """).strip()

    assert wanted == payload 
开发者ID:dalibo,项目名称:ldap2pg,代码行数:26,代码来源:test_config.py

示例11: test_error_handling

# 需要导入模块: import logging [as 别名]
# 或者: from logging import makeLogRecord [as 别名]
def test_error_handling(self):
        h = TestStreamHandler(BadStream())
        r = logging.makeLogRecord({})
        old_raise = logging.raiseExceptions
        old_stderr = sys.stderr
        try:
            h.handle(r)
            self.assertIs(h.error_record, r)
            h = logging.StreamHandler(BadStream())
            sys.stderr = sio = io.StringIO()
            h.handle(r)
            self.assertIn('\nRuntimeError: deliberate mistake\n',
                          sio.getvalue())
            logging.raiseExceptions = False
            sys.stderr = sio = io.StringIO()
            h.handle(r)
            self.assertEqual('', sio.getvalue())
        finally:
            logging.raiseExceptions = old_raise
            sys.stderr = old_stderr

# -- The following section could be moved into a server_helper.py module
# -- if it proves to be of wider utility than just test_logging 
开发者ID:IronLanguages,项目名称:ironpython3,代码行数:25,代码来源:test_logging.py

示例12: test_basic

# 需要导入模块: import logging [as 别名]
# 或者: from logging import makeLogRecord [as 别名]
def test_basic(self):
        sockmap = {}
        server = TestSMTPServer((HOST, 0), self.process_message, 0.001,
                                sockmap)
        server.start()
        addr = (HOST, server.port)
        h = logging.handlers.SMTPHandler(addr, 'me', 'you', 'Log',
                                         timeout=self.TIMEOUT)
        self.assertEqual(h.toaddrs, ['you'])
        self.messages = []
        r = logging.makeLogRecord({'msg': 'Hello \u2713'})
        self.handled = threading.Event()
        h.handle(r)
        self.handled.wait(self.TIMEOUT)  # 14314: don't wait forever
        server.stop()
        self.assertTrue(self.handled.is_set())
        self.assertEqual(len(self.messages), 1)
        peer, mailfrom, rcpttos, data = self.messages[0]
        self.assertEqual(mailfrom, 'me')
        self.assertEqual(rcpttos, ['you'])
        self.assertIn('\nSubject: Log\n', data)
        self.assertTrue(data.endswith('\n\nHello \u2713'))
        h.close() 
开发者ID:IronLanguages,项目名称:ironpython3,代码行数:25,代码来源:test_logging.py

示例13: handle

# 需要导入模块: import logging [as 别名]
# 或者: from logging import makeLogRecord [as 别名]
def handle(self):
        '''
        Handle multiple requests - each expected to be a 4-byte length,
        followed by the LogRecord in pickle format.
        '''
        while 1:
            chunk = self.connection.recv(4)
            if len(chunk) < 4:
                break
            slen = struct.unpack('>L', chunk)[0]
            chunk = self.connection.recv(slen)
            while len(chunk) < slen:
                chunk = chunk + self.connection.recv(slen - len(chunk))
            obj = self.unPickle(chunk)
            record = logging.makeLogRecord(obj)
            self.handleLogRecord(record) 
开发者ID:automl,项目名称:HPOlib,代码行数:18,代码来源:LoggingWebMonitor.py

示例14: handle_stream

# 需要导入模块: import logging [as 别名]
# 或者: from logging import makeLogRecord [as 别名]
def handle_stream(self, stream, address):
        unpacker = msgpack.Unpacker(raw=False)
        while True:
            try:
                wire_bytes = yield stream.read_bytes(1024, partial=True)
                if not wire_bytes:
                    break
                try:
                    unpacker.feed(wire_bytes)
                except msgpack.exceptions.BufferFull:
                    # Start over loosing some data?!
                    unpacker = msgpack.Unpacker(raw=False)
                    unpacker.feed(wire_bytes)
                for record_dict in unpacker:
                    record = logging.makeLogRecord(record_dict)
                    logger = logging.getLogger(record.name)
                    logger.handle(record)
            except (EOFError, KeyboardInterrupt, SystemExit, StreamClosedError):
                break
            except Exception as exc:  # pylint: disable=broad-except
                log.exception(exc) 
开发者ID:saltstack,项目名称:pytest-salt,代码行数:23,代码来源:log_server_tornado.py

示例15: write

# 需要导入模块: import logging [as 别名]
# 或者: from logging import makeLogRecord [as 别名]
def write(self, data):
        data = str(data)
        if data == '\n':
            # when print(data) is invoked, it invokes write() twice. First,
            # writes the data, then writes a new line. This is to avoid
            # emitting log record with just a new-line character.
            return

        # creates https://docs.python.org/2/library/logging.html#logrecord-objects
        file_name, line_number = inspect.getouterframes(inspect.currentframe())[1][1:3]
        record = logging.makeLogRecord({"created": time.time(),
                                        "msg": data,
                                        "filename": os.path.basename(file_name),
                                        "lineno": line_number,
                                        "levelname": "DEBUG",
                                        "levelno": logging.DEBUG})
        self.emit(record) 
开发者ID:dzimine,项目名称:greengo,代码行数:19,代码来源:local_cloudwatch_handler.py


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