Python logging._nameToLevel() Examples

The following are 20 code examples for showing how to use logging._nameToLevel(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module logging , or try the search function .

Example 1
Project: apollo   Author: src-d   File: __main__.py    License: GNU General Public License v3.0 6 votes vote down vote up
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) 
Example 2
Project: pysoa   Author: eventbrite   File: server.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 3
Project: misp42splunk   Author: remg427   File: search_command.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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) 
Example 4
Project: misp42splunk   Author: remg427   File: search_command.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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) 
Example 5
Project: misp42splunk   Author: remg427   File: search_command.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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) 
Example 6
Project: misp42splunk   Author: remg427   File: search_command.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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) 
Example 7
Project: misp42splunk   Author: remg427   File: search_command.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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) 
Example 8
Project: modelforge   Author: src-d   File: slogging.py    License: Apache License 2.0 5 votes vote down vote up
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 
Example 9
Project: fragile   Author: FragileTech   File: slogging.py    License: MIT License 5 votes vote down vote up
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 
Example 10
Project: eyeD3   Author: nicfit   File: __init__.py    License: GNU General Public License v3.0 5 votes vote down vote up
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) 
Example 11
Project: SplunkAdmins   Author: gjanders   File: search_command.py    License: Apache License 2.0 5 votes vote down vote up
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) 
Example 12
Project: SplunkAdmins   Author: gjanders   File: search_command.py    License: Apache License 2.0 5 votes vote down vote up
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) 
Example 13
Project: naz   Author: komuw   File: log.py    License: MIT License 5 votes vote down vote up
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) 
Example 14
Project: naz   Author: komuw   File: log.py    License: MIT License 5 votes vote down vote up
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 
Example 15
Project: python-aspectlib   Author: ionelmc   File: test.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, logger, level='DEBUG'):
        self._logger = logger
        self._level = nameToLevel[level]
        self._calls = []
        self._rollback = None 
Example 16
Project: swagger-marshmallow-codegen   Author: podhmo   File: cmd.py    License: MIT License 5 votes vote down vote up
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) 
Example 17
Project: vscode-extension-splunk   Author: splunk   File: search_command.py    License: MIT License 5 votes vote down vote up
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) 
Example 18
Project: modelforge   Author: src-d   File: slogging.py    License: Apache License 2.0 4 votes vote down vote up
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) 
Example 19
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 
Example 20
Project: fragile   Author: FragileTech   File: slogging.py    License: MIT License 4 votes vote down vote up
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)