本文整理汇总了Python中logging._nameToLevel方法的典型用法代码示例。如果您正苦于以下问题:Python logging._nameToLevel方法的具体用法?Python logging._nameToLevel怎么用?Python logging._nameToLevel使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类logging
的用法示例。
在下文中一共展示了logging._nameToLevel方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: import logging [as 别名]
# 或者: from logging import _nameToLevel [as 别名]
def main():
"""
Creates all the argument parsers and invokes the function from set_defaults().
:return: The result of the function from set_defaults().
"""
parser = get_parser()
args = parser.parse_args()
args.log_level = logging._nameToLevel[args.log_level]
setup_logging(args.log_level)
try:
handler = args.handler
except AttributeError:
def print_usage(_):
parser.print_usage()
handler = print_usage
return handler(args)
示例2: __init__
# 需要导入模块: import logging [as 别名]
# 或者: from logging import _nameToLevel [as 别名]
def __init__(
self,
logger, # type: Union[six.text_type, six.binary_type, logging.Logger, None]
level, # type: Union[six.text_type, six.binary_type, int, None]
):
if isinstance(logger, logging.Logger):
self.logger = logger
self.logger_name = logger.name # type: Union[six.text_type, six.binary_type, None]
else:
# noinspection PyTypeChecker
self.logger = logging.getLogger(logger) # type: ignore
self.logger_name = logger
if level:
if isinstance(level, int):
self.level = level
else:
if six.PY2:
# noinspection PyProtectedMember,PyUnresolvedReferences
self.level = logging._levelNames[level] # type: ignore
else:
# noinspection PyProtectedMember
self.level = logging._nameToLevel[level] # type: ignore
else:
self.level = logging.INFO
示例3: logging_level
# 需要导入模块: import logging [as 别名]
# 或者: from logging import _nameToLevel [as 别名]
def logging_level(self, value):
if value is None:
value = self._default_logging_level
if isinstance(value, (bytes, six.text_type)):
try:
level = _levelNames[value.upper()]
except KeyError:
raise ValueError('Unrecognized logging level: {}'.format(value))
else:
try:
level = int(value)
except ValueError:
raise ValueError('Unrecognized logging level: {}'.format(value))
self._logger.setLevel(level)
示例4: add_logging_args
# 需要导入模块: import logging [as 别名]
# 或者: from logging import _nameToLevel [as 别名]
def add_logging_args(parser: argparse.ArgumentParser, patch: bool = True,
erase_args: bool = True) -> None:
"""
Add command line flags specific to logging.
:param parser: `argparse` parser where to add new flags.
:param erase_args: Automatically remove logging-related flags from parsed args.
:param patch: Patch parse_args() to automatically setup logging.
"""
parser.add_argument("--log-level", default="INFO", choices=logging._nameToLevel,
help="Logging verbosity.")
parser.add_argument("--log-structured", action="store_true",
help="Enable structured logging (JSON record per line).")
parser.add_argument("--log-config",
help="Path to the file which sets individual log levels of domains.")
# monkey-patch parse_args()
# custom actions do not work, unfortunately, because they are not invoked if
# the corresponding --flags are not specified
def _patched_parse_args(args=None, namespace=None) -> argparse.Namespace:
args = parser._original_parse_args(args, namespace)
setup(args.log_level, args.log_structured, args.log_config)
if erase_args:
for log_arg in ("log_level", "log_structured", "log_config"):
delattr(args, log_arg)
return args
if patch and not hasattr(parser, "_original_parse_args"):
parser._original_parse_args = parser.parse_args
parser.parse_args = _patched_parse_args
示例5: add_logging_args
# 需要导入模块: import logging [as 别名]
# 或者: from logging import _nameToLevel [as 别名]
def add_logging_args(
parser: argparse.ArgumentParser, patch: bool = True, erase_args: bool = True
) -> None:
"""
Add command line flags specific to logging.
Args:
parser: `argparse` parser where to add new flags.
erase_args: Automatically remove logging-related flags from parsed args.
patch: Patch parse_args() to automatically setup logging.
"""
parser.add_argument(
"--log-level", default="INFO", choices=logging._nameToLevel, help="Logging verbosity."
)
parser.add_argument(
"--log-structured",
action="store_true",
help="Enable structured logging (JSON record per line).",
)
parser.add_argument(
"--log-config", help="Path to the file which sets individual log levels of domains."
)
# monkey-patch parse_args()
# custom actions do not work, unfortunately, because they are not invoked if
# the corresponding --flags are not specified
def _patched_parse_args(args=None, namespace=None) -> argparse.Namespace:
args = parser._original_parse_args(args, namespace)
setup(args.log_level, args.log_structured, args.log_config)
if erase_args:
for log_arg in ("log_level", "log_structured", "log_config"):
delattr(args, log_arg)
return args
if patch and not hasattr(parser, "_original_parse_args"):
parser._original_parse_args = parser.parse_args
parser.parse_args = _patched_parse_args
示例6: __call__
# 需要导入模块: import logging [as 别名]
# 或者: from logging import _nameToLevel [as 别名]
def __call__(self, parser, namespace, values, option_string=None):
values = values.split(':')
level, logger = values if len(values) > 1 else (values[0],
self.main_logger)
logger = logging.getLogger(logger)
try:
logger.setLevel(logging._nameToLevel[level.upper()])
except KeyError:
msg = f"invalid level choice: {level} (choose from {parser.log_levels})"
raise argparse.ArgumentError(self, msg)
super(LoggingAction, self).__call__(parser, namespace, values, option_string)
示例7: log
# 需要导入模块: import logging [as 别名]
# 或者: from logging import _nameToLevel [as 别名]
def log(self, level, msg, *args, **kwargs):
"""
Log 'msg % args' with the integer severity 'level'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.log(level, "We have a %s", "mysterious problem", exc_info=1)
"""
if self._nameToLevel(level) >= logging.ERROR:
kwargs.update(dict(exc_info=True))
new_msg = self._process_msg(msg)
return super(SimpleLogger, self).log(level, new_msg, *args, **kwargs)
示例8: _nameToLevel
# 需要导入模块: import logging [as 别名]
# 或者: from logging import _nameToLevel [as 别名]
def _nameToLevel(level: typing.Union[str, int]) -> int:
try:
if isinstance(level, str):
# please mypy
_level: int = logging._nameToLevel[level.upper()]
else:
_level = level
return _level
except KeyError as e:
raise ValueError(
"`level` should be one of; 'NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'"
) from e
示例9: __init__
# 需要导入模块: import logging [as 别名]
# 或者: from logging import _nameToLevel [as 别名]
def __init__(self, logger, level='DEBUG'):
self._logger = logger
self._level = nameToLevel[level]
self._calls = []
self._rollback = None
示例10: main
# 需要导入模块: import logging [as 别名]
# 或者: from logging import _nameToLevel [as 别名]
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--driver", default="Driver")
parser.add_argument(
"--logging",
default="INFO",
choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
)
parser.add_argument("--full", action="store_true")
parser.add_argument("--legacy", action="store_true")
parser.add_argument("file", default=None)
args = parser.parse_args()
logging.basicConfig(
format="%(levelname)5s:%(name)36s:%(message)s",
level=logging._nameToLevel[args.logging],
)
driver_cls = args.driver
if args.legacy and driver_cls == "Driver": # xxx
logger.info("legacy option is added. output Schema is legacy flavor")
driver_cls = "LegacyDriver"
if ":" not in driver_cls:
driver_cls = "swagger_marshmallow_codegen.driver:{}".format(driver_cls)
if args.full:
options = {"targets": {"schema": True, "input": True, "output": True}}
else:
options = {"targets": {"schema": True}}
driver = import_symbol(driver_cls, cwd=True)(options)
if args.file is None:
driver.run(sys.stdin, sys.stdout)
else:
with open(args.file) as rf:
driver.run(rf, sys.stdout)
示例11: setup
# 需要导入模块: import logging [as 别名]
# 或者: from logging import _nameToLevel [as 别名]
def setup(level: Union[str, int], structured: bool, config_path: str = None):
"""
Make stdout and stderr unicode friendly in case of misconfigured \
environments, initializes the logging, structured logging and \
enables colored logs if it is appropriate.
:param level: The global logging level.
:param structured: Output JSON logs to stdout.
:param config_path: Path to a yaml file that configures the level of output of the loggers. \
Root logger level is set through the level argument and will override any \
root configuration found in the conf file.
:return: None
"""
global logs_are_structured
logs_are_structured = structured
if not isinstance(level, int):
level = logging._nameToLevel[level]
def ensure_utf8_stream(stream):
if not isinstance(stream, io.StringIO) and hasattr(stream, "buffer"):
stream = codecs.getwriter("utf-8")(stream.buffer)
stream.encoding = "utf-8"
return stream
sys.stdout, sys.stderr = (ensure_utf8_stream(s)
for s in (sys.stdout, sys.stderr))
# basicConfig is only called to make sure there is at least one handler for the root logger.
# All the output level setting is down right afterwards.
logging.basicConfig()
logging.setLogRecordFactory(NumpyLogRecord)
if config_path is not None and os.path.isfile(config_path):
with open(config_path) as fh:
config = yaml.safe_load(fh)
for key, val in config.items():
logging.getLogger(key).setLevel(logging._nameToLevel.get(val, level))
root = logging.getLogger()
root.setLevel(level)
if not structured:
handler = root.handlers[0]
handler.emit = check_trailing_dot(handler.emit)
if not sys.stdin.closed and sys.stdout.isatty():
handler.setFormatter(AwesomeFormatter())
else:
root.handlers[0] = StructuredHandler(level)
示例12: logger
# 需要导入模块: import logging [as 别名]
# 或者: from logging import _nameToLevel [as 别名]
def logger():
getpid_patch = patch('logging.os.getpid', return_value=111)
getpid_patch.start()
time_patch = patch('logging.time.time', return_value=946725071.111111)
time_patch.start()
localzone_patch = patch('rfc5424logging.handler.get_localzone', return_value=timezone)
localzone_patch.start()
hostname_patch = patch('rfc5424logging.handler.socket.gethostname', return_value="testhostname")
hostname_patch.start()
connect_patch = patch('logging.handlers.socket.socket.connect', side_effect=connect_mock)
connect_patch.start()
sendall_patch = patch('logging.handlers.socket.socket.sendall', side_effect=connect_mock)
sendall_patch.start()
if '_levelNames' in logging.__dict__:
# Python 2.7
level_patch = patch.dict(logging._levelNames)
level_patch.start()
else:
# Python 3.x
level_patch1 = patch.dict(logging._levelToName)
level_patch1.start()
level_patch2 = patch.dict(logging._nameToLevel)
level_patch2.start()
logging.raiseExceptions = True
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
yield logger
getpid_patch.stop()
time_patch.stop()
localzone_patch.stop()
hostname_patch.stop()
connect_patch.stop()
sendall_patch.stop()
if '_levelNames' in logging.__dict__:
# Python 2.7
level_patch.stop()
else:
# Python 3.x
level_patch1.stop()
level_patch2.stop()
Rfc5424SysLogAdapter._extra_levels_enabled = False
示例13: setup
# 需要导入模块: import logging [as 别名]
# 或者: from logging import _nameToLevel [as 别名]
def setup(level: Union[str, int], structured: bool, config_path: str = None):
"""
Make stdout and stderr unicode friendly in case of misconfigured \
environments, initializes the logging, structured logging and \
enables colored logs if it is appropriate.
Args:
level: The global logging level.
structured: Output JSON logs to stdout.
config_path: Path to a yaml file that configures the level of output of the loggers. \
Root logger level is set through the level argument and will override any \
root configuration found in the conf file.
Returns:
None
"""
global logs_are_structured
logs_are_structured = structured
if not isinstance(level, int):
level = logging._nameToLevel[level]
def ensure_utf8_stream(stream):
if not isinstance(stream, io.StringIO) and hasattr(stream, "buffer"):
stream = codecs.getwriter("utf-8")(stream.buffer)
stream.encoding = "utf-8"
return stream
sys.stdout, sys.stderr = (ensure_utf8_stream(s) for s in (sys.stdout, sys.stderr))
# basicConfig is only called to make sure there is at least one handler for the root logger.
# All the output level setting is down right afterwards.
logging.basicConfig()
logging.setLogRecordFactory(NumpyLogRecord)
if config_path is not None and os.path.isfile(config_path):
with open(config_path) as fh:
config = yaml.safe_load(fh)
for key, val in config.items():
logging.getLogger(key).setLevel(logging._nameToLevel.get(val, level))
root = logging.getLogger()
root.setLevel(level)
if not structured:
handler = root.handlers[0]
handler.emit = check_trailing_dot(handler.emit)
if not hasattr(sys.stdin, "closed"):
handler.setFormatter(AwesomeFormatter())
elif not sys.stdin.closed and sys.stdout.isatty():
handler.setFormatter(AwesomeFormatter())
else:
root.handlers[0] = StructuredHandler(level)