本文整理汇总了Python中logging.LogRecord方法的典型用法代码示例。如果您正苦于以下问题:Python logging.LogRecord方法的具体用法?Python logging.LogRecord怎么用?Python logging.LogRecord使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类logging
的用法示例。
在下文中一共展示了logging.LogRecord方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: format
# 需要导入模块: import logging [as 别名]
# 或者: from logging import LogRecord [as 别名]
def format(self, record: logging.LogRecord) -> str:
record_clone = copy.copy(record)
record_clone.__dict__.update(self._colordict)
if record_clone.levelname in self._log_colors:
color = self._log_colors[record_clone.levelname]
color_str = self._colordict[color]
record_clone.log_color = color_str # type: ignore[attr-defined]
else:
record_clone.log_color = '' # type: ignore[attr-defined]
for field in ['msg', 'filename', 'funcName', 'levelname', 'module',
'name', 'pathname', 'processName', 'threadName']:
data = str(getattr(record_clone, field))
setattr(record_clone, field, pyhtml.escape(data))
msg = super().format(record_clone)
if not msg.endswith(self._colordict['reset']):
msg += self._colordict['reset']
return msg
示例2: _emit
# 需要导入模块: import logging [as 别名]
# 或者: from logging import LogRecord [as 别名]
def _emit(self, record: logging.LogRecord) -> None:
# JSON conversion based on Marsel Mavletkulov's json-log-formatter (MIT license)
# https://github.com/marselester/json-log-formatter
content = {
name: value
for name, value in record.__dict__.items()
if name not in EXCLUDE_ATTRS
}
content["id"] = str(record.relativeCreated)
content["msg"] = record.getMessage()
content["time"] = datetime.fromtimestamp(record.created)
if record.exc_info:
content["exc_info"] = self.formatter.formatException(record.exc_info)
for name, value in content.items():
if isinstance(value, datetime):
content[name] = value.astimezone().isoformat()
asyncio.run_coroutine_threadsafe(self.send(content), loop=self.loop)
self.lines.append(content)
示例3: test_RawFileHandler_appends_binary_message_into_logfile
# 需要导入模块: import logging [as 别名]
# 或者: from logging import LogRecord [as 别名]
def test_RawFileHandler_appends_binary_message_into_logfile():
import os.path
from moler.config.loggers import RAW_DATA, RawFileHandler
cwd = os.getcwd()
logfile_full_path = os.path.join(cwd, "tmp.raw.log")
raw_handler = RawFileHandler(filename=logfile_full_path, mode='wb')
binary_msg = b"1 0.000000000 127.0.0.1 \xe2\x86\x92 127.0.0.1 ICMP 98 Echo (ping) request id=0x693b, seq=48/12288, ttl=64"
record = logging.LogRecord(name=None, level=RAW_DATA, pathname="", lineno=0,
msg=binary_msg, # only this is used
args=(), exc_info=None)
raw_handler.emit(record=record)
raw_handler.close()
with open(logfile_full_path, mode='rb') as logfh:
content = logfh.read()
assert content == binary_msg
os.remove(logfile_full_path)
示例4: check_trailing_dot
# 需要导入模块: import logging [as 别名]
# 或者: from logging import LogRecord [as 别名]
def check_trailing_dot(func: Callable) -> Callable:
"""
Decorate a function to check if the log message ends with a dot.
AssertionError is raised if so.
"""
@functools.wraps(func)
def decorated_with_check_trailing_dot(record: logging.LogRecord):
if record.name not in trailing_dot_exceptions:
msg = record.msg
if isinstance(msg, str) and msg.endswith(".") and not msg.endswith(".."):
raise AssertionError(
"Log message is not allowed to have a trailing dot: %s: \"%s\"" %
(record.name, msg))
return func(record)
return decorated_with_check_trailing_dot
示例5: getMessage
# 需要导入模块: import logging [as 别名]
# 或者: from logging import LogRecord [as 别名]
def getMessage(self):
"""
Return the message for this LogRecord.
Return the message for this LogRecord after merging any user-supplied \
arguments with the message.
"""
if isinstance(self.msg, numpy.ndarray):
msg = self.array2string(self.msg)
else:
msg = str(self.msg)
if self.args:
a2s = self.array2string
if isinstance(self.args, Dict):
args = {k: (a2s(v) if isinstance(v, numpy.ndarray) else v)
for (k, v) in self.args.items()}
elif isinstance(self.args, Sequence):
args = tuple((a2s(a) if isinstance(a, numpy.ndarray) else a)
for a in self.args)
else:
raise TypeError("Unexpected input '%s' with type '%s'" % (self.args,
type(self.args)))
msg = msg % args
return msg
示例6: formatMessage
# 需要导入模块: import logging [as 别名]
# 或者: from logging import LogRecord [as 别名]
def formatMessage(self, record: logging.LogRecord) -> str:
"""Convert the already filled log record to a string."""
level_color = "0"
text_color = "0"
fmt = ""
if record.levelno <= logging.DEBUG:
fmt = "\033[0;37m" + logging.BASIC_FORMAT + "\033[0m"
elif record.levelno <= logging.INFO:
level_color = "1;36"
lmsg = record.message.lower()
if self.GREEN_RE.search(lmsg):
text_color = "1;32"
elif record.levelno <= logging.WARNING:
level_color = "1;33"
elif record.levelno <= logging.CRITICAL:
level_color = "1;31"
if not fmt:
fmt = "\033[" + level_color + \
"m%(levelname)s\033[0m:%(rthread)s:%(name)s:\033[" + text_color + \
"m%(message)s\033[0m"
fmt = _fest + fmt
record.rthread = reduce_thread_id(record.thread)
return fmt % record.__dict__
示例7: emit
# 需要导入模块: import logging [as 别名]
# 或者: from logging import LogRecord [as 别名]
def emit(self, record: logging.LogRecord):
"""Print the log record formatted as JSON to stdout."""
created = datetime.datetime.fromtimestamp(record.created, timezone)
obj = {
"level": record.levelname.lower(),
"msg": record.msg % record.args,
"source": "%s:%d" % (record.filename, record.lineno),
"time": format_datetime(created),
"thread": reduce_thread_id(record.thread),
}
if record.exc_info is not None:
obj["error"] = traceback.format_exception(*record.exc_info)[1:]
try:
obj["context"] = self.local.context
except AttributeError:
pass
json.dump(obj, sys.stdout, sort_keys=True)
sys.stdout.write("\n")
sys.stdout.flush()
示例8: merge_record_extra
# 需要导入模块: import logging [as 别名]
# 或者: from logging import LogRecord [as 别名]
def merge_record_extra(record, target, reserved):
"""
Merges extra attributes from LogRecord object into target dictionary
:param record: logging.LogRecord
:param target: dict to update
:param reserved: dict or list with reserved keys to skip
"""
for key, value in record.__dict__.items():
# this allows to have numeric keys
if key not in reserved:
if not hasattr(key, 'startswith') or not key.startswith('_'):
target[key] = value
return target
# https://stackoverflow.com/questions/384076/how-can-i-color-python-logging-output
示例9: get_qkc_log_prefix
# 需要导入模块: import logging [as 别名]
# 或者: from logging import LogRecord [as 别名]
def get_qkc_log_prefix(record: logging.LogRecord):
"""Returns the absl-like log prefix for the log record.
Args:
record: logging.LogRecord, the record to get prefix for.
"""
created_tuple = time.localtime(record.created)
created_microsecond = int(record.created % 1.0 * 1e6)
level = record.levelno
severity = get_colored_initial_for_level(level)
end_severity = get_end_color_for_level(level)
return "%s%02d%02d%s %02d:%02d:%02d.%06d %s:%d] " % (
severity,
created_tuple.tm_mon,
created_tuple.tm_mday,
end_severity,
created_tuple.tm_hour,
created_tuple.tm_min,
created_tuple.tm_sec,
created_microsecond,
record.filename,
record.lineno,
)
示例10: get_records
# 需要导入模块: import logging [as 别名]
# 或者: from logging import LogRecord [as 别名]
def get_records(self, when):
"""
Get the logging records for one of the possible test phases.
:param str when:
Which test phase to obtain the records from. Valid values are: "setup", "call" and "teardown".
:rtype: List[logging.LogRecord]
:return: the list of captured records at the given stage
.. versionadded:: 3.4
"""
handler = self._item.catch_log_handlers.get(when)
if handler:
return handler.records
else:
return []
示例11: setup_once
# 需要导入模块: import logging [as 别名]
# 或者: from logging import LogRecord [as 别名]
def setup_once():
# type: () -> None
old_callhandlers = logging.Logger.callHandlers # type: ignore
def sentry_patched_callhandlers(self, record):
# type: (Any, LogRecord) -> Any
try:
return old_callhandlers(self, record)
finally:
# This check is done twice, once also here before we even get
# the integration. Otherwise we have a high chance of getting
# into a recursion error when the integration is resolved
# (this also is slower).
if record.name not in _IGNORED_LOGGERS:
integration = Hub.current.get_integration(LoggingIntegration)
if integration is not None:
integration._handle_record(record)
logging.Logger.callHandlers = sentry_patched_callhandlers # type: ignore
示例12: get_record
# 需要导入模块: import logging [as 别名]
# 或者: from logging import LogRecord [as 别名]
def get_record(self):
"""Make a fake record."""
os.environ['BOT_NAME'] = 'linux-bot'
os.environ['TASK_PAYLOAD'] = 'fuzz fuzzer1 job1'
record = mock.Mock(
specset=logging.LogRecord,
levelname='INFO',
exc_info='exc_info',
created=10,
location={
'path': 'path',
'line': 123,
'method': 'func'
})
record.name = 'logger_name'
record.getMessage.return_value = 'log message'
return record
示例13: test_format_record
# 需要导入模块: import logging [as 别名]
# 或者: from logging import LogRecord [as 别名]
def test_format_record(self):
"""Test format a LogRecord into JSON string."""
os.environ['FUZZ_TARGET'] = 'fuzz_target1'
record = self.get_record()
record.extras = {'a': 1}
self.assertEqual({
'message': 'log message',
'created': '1970-01-01T00:00:10Z',
'severity': 'INFO',
'bot_name': 'linux-bot',
'task_payload': 'fuzz fuzzer1 job1',
'fuzz_target': 'fuzz_target1',
'name': 'logger_name',
'extras': {
'a': 1,
},
'location': {
'path': 'path',
'line': 123,
'method': 'func'
}
}, json.loads(logs.format_record(record)))
self.mock.update_entry_with_exc.assert_called_once_with(
mock.ANY, 'exc_info')
示例14: emit
# 需要导入模块: import logging [as 别名]
# 或者: from logging import LogRecord [as 别名]
def emit(self, record: logging.LogRecord) -> None: # pragma: no cover
# Get corresponding Loguru level if it exists
try:
level = logger.level(record.levelname).name
except ValueError:
level = str(record.levelno)
# Find caller from where originated the logged message
frame, depth = logging.currentframe(), 2
while frame.f_code.co_filename == logging.__file__: # noqa: WPS609
frame = cast(FrameType, frame.f_back)
depth += 1
logger.opt(depth=depth, exception=record.exc_info).log(
level, record.getMessage(),
)
示例15: check_trailing_dot
# 需要导入模块: import logging [as 别名]
# 或者: from logging import LogRecord [as 别名]
def check_trailing_dot(func: Callable) -> Callable:
"""
Decorate a function to check if the log message ends with a dot.
AssertionError is raised if so.
"""
@functools.wraps(func)
def decorated_with_check_trailing_dot(record: logging.LogRecord):
if record.name not in trailing_dot_exceptions:
msg = record.msg
if isinstance(msg, str) and msg.endswith(".") and not msg.endswith(".."):
raise AssertionError(
'Log message is not allowed to have a trailing dot: %s: "%s"'
% (record.name, msg)
)
return func(record)
return decorated_with_check_trailing_dot