Python logging._nameToLevel() Examples

The following are code examples for showing how to use logging._nameToLevel(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: magne   Author: allenling   File: run.py    MIT License 6 votes vote down vote up
def main():
    parser = get_parser()
    args = parser.parse_args()
    worker_nums = args.workers
    worker_timeout = args.worker_timeout
    task_module = args.task
    qos = args.qos if args.qos >= 0 else worker_nums
    amqp_url = args.amqp_url
    threads = args.threads
    logger_level = args.log_level.upper()
    if logger_level not in logging._nameToLevel:
        raise Exception('invalid log level')
    logger_level = logging._nameToLevel[logger_level]
    cdebug = args.curio_debug
    # worker进程数暂时没用
    magne_thread_main(worker_timeout, task_module, threads, qos, amqp_url, logger_level, cdebug)
    return 
Example 2
Project: epylog   Author: iPhosgen   File: logger.py    MIT License 6 votes vote down vote up
def __validate_rules(cls):
        for rule in cls.configuration['rules']:
            rule['_is_valid'] = True

            # Validate rule name
            if not rule.get('name', False):
                cls.logger.warning('Invalid rule name. Rule: %s', rule)
                rule['_is_valid'] = False
                continue

            # Validate rule min LEVEL
            if not rule.get('min-level', False) or rule['min-level'].upper() not in logging._nameToLevel.keys():
                cls.logger.warning('Invalid rule min LEVEL. Rule: %s', rule)
                rule['_is_valid'] = False
                continue

            # Validate write to
            if not rule.get('write-to', False) and not all(elem in rule['write-to'].split(',') for elem in cls.targets.keys()):
                cls.logger.warning('Invalid rule write to. Rule: %s', rule)
                rule['_is_valid'] = False
                continue
            rule['write-to'] = rule['write-to'].split(',') 
Example 3
Project: beqdesigner   Author: 3ll3d00d   File: log.py    MIT License 6 votes vote down vote up
def __init__(self, preferences, size=1000, parent=None):
        super().__init__()
        self.__buffer = RingBuffer(size, dtype=np.object)
        self.__signals = MessageSignals()
        self.__visible = False
        self.__window = None
        self.__preferences = preferences
        self.__excludes = []
        self.parent = parent
        self.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(threadName)s	- %(name)s - %(funcName)s - %(message)s'))
        level = self.__preferences.get(LOGGING_LEVEL)
        if level is not None and level in logging._nameToLevel:
            level = logging._nameToLevel[level]
        else:
            level = logging.INFO
        self.__root = self.__init_root_logger(level)
        self.__levelName = logging.getLevelName(level) 
Example 4
Project: shell-complete   Author: src-d   File: __main__.py    Apache License 2.0 6 votes vote down vote up
def main():
    """
    Creates all the argparse-rs 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 5
Project: PyAutoFit   Author: rhayes777   File: non_linear.py    MIT License 6 votes vote down vote up
def __init__(self, paths):
        """Abstract base class for non-linear optimizers.

        This class sets up the file structure for the non-linear optimizer nlo, which are standardized across \
        all non-linear optimizers.

        Parameters
        ------------

        """
        log_file = conf.instance.general.get("output", "log_file", str).replace(" ", "")
        self.paths = paths

        if not len(log_file) == 0:
            log_path = "{}/{}".format(self.paths.phase_output_path, log_file)
            logger.handlers = [logging.FileHandler(log_path)]
            logger.propagate = False
            # noinspection PyProtectedMember
            logger.level = logging._nameToLevel[
                conf.instance.general.get("output", "log_level", str)
                .replace(" ", "")
                .upper()
            ]

        self.paths.restore() 
Example 6
Project: primrose   Author: ww-tech   File: logging_success.py    Apache License 2.0 6 votes vote down vote up
def run(self, data_object):
        """Signal success by logging a message at specified log level

        Args:
            data_object (DataObject): DataObject instance

        Returns:
            nothing. Side effect is to signal success via logging

        """
        msg = self.node_config['msg']

        level = str(self.node_config['level']).upper()

        # check whether valid level: will throw KeyError if level not recognized
        logging._nameToLevel[level]

        level = logging.getLevelName(level)

        logging.getLogger("")._log(level, msg, None, None)

        terminate = False

        return data_object, terminate 
Example 7
Project: misp42splunk   Author: remg427   File: search_command.py    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: misp42splunk   Author: remg427   File: search_command.py    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 9
Project: SplunkVersionControl   Author: gjanders   File: search_command.py    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 10
Project: magne   Author: allenling   File: run.py    MIT License 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(prog='magne coroutine', description='magne coroutine worker')
    parser.add_argument('--task', type=str, help='task module path, default: magne.coro_consumer.demo_task',
                        default='magne.coro_consumer.demo_task')
    parser.add_argument('--amqp-url', type=str, help='amqp address, default: amqp://guest:[email protected]:5672//',
                        default='amqp://guest:[email protected]:5672//',
                        )
    parser.add_argument('--timeout', type=int, help='worker timeout, default 60s',
                        default=60,
                        )
    parser.add_argument('--qos', type=int, help='prefetch count, default 0',
                        default=0,
                        )
    parser.add_argument('--log-level', type=str, help='any level in logging, default: INFO',
                        default='INFO',
                        )
    parser.add_argument('--curio-debug', type=int, help='curio monitor, default: 0, any greater than 0 will start debug',
                        default=0,
                        )
    args = parser.parse_args()
    timeout = args.timeout
    task_module = args.task
    qos = args.qos
    amqp_url = args.amqp_url
    log_level = args.log_level.upper()
    if log_level not in logging._nameToLevel:
        raise Exception('invalid log level')
    log_level = logging._nameToLevel[log_level]
    curio_debug = True if args.curio_debug > 0 else False
    coro_main(timeout, task_module, qos, amqp_url, log_level, curio_debug)
    return 
Example 11
Project: magne   Author: allenling   File: run.py    MIT License 5 votes vote down vote up
def main():
    parser = get_parser()
    args = parser.parse_args()
    worker_nums = args.workers
    worker_timeout = args.worker_timeout
    task_module = args.task
    qos = args.qos if args.qos >= 0 else worker_nums
    amqp_url = args.amqp_url
    logger_level = args.log_level.upper()
    if logger_level not in logging._nameToLevel:
        raise Exception('invalid log level')
    logger_level = logging._nameToLevel[logger_level]
    magne_main(worker_nums, worker_timeout, task_module, amqp_url, qos, logger_level)
    return 
Example 12
Project: modelforge   Author: src-d   File: slogging.py    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 13
Project: epylog   Author: iPhosgen   File: logger.py    MIT License 5 votes vote down vote up
def getLogger(cls, name):
        """Returns Logger object with specified settings"""

        logger = logging.getLogger(name)

        if not cls.configuration:
            cls.__read_config_file()

        if cls.configuration['_is_valid']:
            datefmt = "%Y-%m-%d,%H:%M:%S"
            for rule in [rule for rule in cls.configuration['rules'] if rule['_is_valid']]:
                if name.startswith(rule['name'].split('*')[0]):
                    logger.handlers.clear()

                    for target in rule['write-to']:
                        handler = cls.targets[target]

                        formatter = {}
                        if rule.get('format', False):
                            formatter = logging.Formatter(rule['format'],
                                                          datefmt=datefmt)
                        else:
                            formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s",
                                                          datefmt=datefmt)

                        handler.setFormatter(formatter)

                        logger.addHandler(handler)

                    logger.setLevel(logging._nameToLevel[rule['min-level'].upper()])

                    return logger

        logger.setLevel(logging.INFO)
        return logger 
Example 14
Project: eyeD3   Author: nicfit   File: __init__.py    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 15
Project: SplunkAdmins   Author: gjanders   File: search_command.py    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 16
Project: pathpy   Author: pathpy   File: logger.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def logger(name, level=None):
    """A function to generate logger for the modules."""

    # initialize new logger
    logger = logging.getLogger(name)

    # logging messages are not passed to the handlers of ancestor loggers
    logger.propagate = False

    # get formatter options
    logger.addHandler(console)

    # if no level is defined the config level will be used
    if level is None:
        logger.setLevel(logging._nameToLevel[config['logging']['level']])
    else:
        logger.setLevel(logging._nameToLevel[level])
    return logger


# =============================================================================
# eof
#
# Local Variables:
# mode: python
# mode: linum
# mode: auto-fill
# fill-column: 79
# End: 
Example 17
Project: stash-scanner   Author: senuido   File: AppGUI.py    GNU General Public License v3.0 5 votes vote down vote up
def set_msglevel(self, event):
        self.msg_level = logging._nameToLevel[self.cmb_msglevel.get().upper()] 
Example 18
Project: network2tikz   Author: hackl   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def logger(name, level='INFO'):
    """A function to generate logger for the modules."""
    # initialize new logger
    logger = logging.getLogger(name)
    # set logger level
    logger.setLevel(logging._nameToLevel[level])
    return logger 
Example 19
Project: os-sanic   Author: cfhamlet   File: config.py    MIT License 5 votes vote down vote up
def valid_log_level(cls, v):
        if v.upper() not in _nameToLevel:
            raise ValidationError(f'Invalid log level {v}')
        return v 
Example 20
Project: tm-experiments   Author: src-d   File: cli.py    Apache License 2.0 5 votes vote down vote up
def _define_parser() -> ArgumentParser:
    parser = ArgumentParser()
    subparsers = parser.add_subparsers(help="Commands")
    for name, (help, parser_definer, handler) in _commands.items():
        subparser = subparsers.add_parser(name, help=help)
        subparser.set_defaults(handler=handler)
        parser_definer(subparser)
        subparser.add_argument(
            "--log-level",
            default="INFO",
            choices=logging_name_to_level,
            help="Logging verbosity.",
        )
    return parser 
Example 21
Project: tm-experiments   Author: src-d   File: cli.py    Apache License 2.0 5 votes vote down vote up
def parse_args() -> Tuple[Callable[..., Any], Dict[str, Any]]:
    parser = _define_parser()
    args = parser.parse_args()
    args.log_level = logging_name_to_level[args.log_level]
    handler = args.handler
    delattr(args, "handler")
    return handler, vars(args) 
Example 22
Project: swagger-marshmallow-codegen   Author: podhmo   File: cmd.py    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 23
Project: piny   Author: pilosus   File: flask_integration.py    MIT License 5 votes vote down vote up
def validate_name(cls, value):
        upper = value.upper()
        if upper not in logging._nameToLevel:
            raise ValueError("Invalid logging level")
        return upper 
Example 24
Project: miniutils   Author: scnerd   File: logs_base.py    MIT License 5 votes vote down vote up
def proxy_log(msg, *args, **kwargs):
    if logger is None:
        print(msg, file=sys.stderr, flush=True)
    else:
        lvl = kwargs.pop('log_level', 'INFO')
        if isinstance(lvl, str):
            lvl = logging._nameToLevel[lvl]
        logger.log(lvl, msg, *args, **kwargs) 
Example 25
Project: modelforge   Author: src-d   File: slogging.py    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 26
Project: rfc5424-logging-handler   Author: jobec   File: conftest.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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 27
Project: s4-clarity-lib   Author: SemaphoreSolutions   File: genericscript.py    MIT License 4 votes vote down vote up
def add_arguments(cls, parser):
        """
        Configures the Argument Parser to read command line input
        and store it in the self.options object.

        This method can be overrode in sub classes to provide extra arguments
        specific to the script being written. When this is done it is important to
        call the parent class add_arguemnts methods so that all arguments are included.

        :argument parser: The ArgumentParser that will be used to process the command line.
        :type parser: argparse.ArgumentParser
        """

        parser.add_argument(
            '-n', '--dry-run', action='store_true'
        )

        parser.add_argument(
            '-l', '--logfile', type=argparse.FileType('a'), default=None, nargs='?'
        )

        parser.add_argument(
            '--log-type', type=str, required=False, default='text', choices=['html', 'text']
        )

        def logleveltype(string):
            try:
                return logging.getLevelName(string.upper())
            except KeyError:
                # Log levels are in different properties in Python 2 and 3 modules
                try:
                    # Python 3
                    level_name_dict = logging._nameToLevel
                except:
                    # Python 2
                    level_name_dict = logging._levelNames
                msg = "%r is not a valid log level: use one of %s" % (
                    string,
                    list(filter(lambda k: type(k) == str, level_name_dict.keys()))
                )
                raise argparse.ArgumentTypeError(msg)

        parser.add_argument(
            '--log-level', type=logleveltype, default=logging.INFO,
            help='Logging threshold. Default INFO.'
        )
        # separate level for console log stream for easier debugging
        parser.add_argument(
            '--log-level-console', type=logleveltype, default=logging.ERROR,
            help='Logging threshold for the console. Default ERROR.'
        ) 
Example 28
Project: crwy   Author: wuyue92tree   File: logger.py    MIT License 4 votes vote down vote up
def _install_handlers_custom(cp, formatters, log_path):
    """Install and return handlers"""
    hlist = cp.get("handlers", "keys")
    if not len(hlist):
        return {}
    hlist = hlist.split(",")
    hlist = logging.config._strip_spaces(hlist)
    handlers = {}
    fixups = []  # for inter-handler references
    for hand in hlist:
        sectname = "handler_%s" % hand
        klass = cp.get(sectname, "class")
        opts = cp.options(sectname)
        if "formatter" in opts:
            fmt = cp.get(sectname, "formatter")
        else:
            fmt = ""
        try:
            klass = eval(klass, vars(logging))
        except (AttributeError, NameError):
            klass = logging.config._resolve(klass)
        args = cp.get(sectname, "args")
        args = eval(args, vars(logging))

        # 修改args中的path参数
        if isinstance(args[0], str):
            args = tuple([log_path] + list(args)[1:])

        h = klass(*args)

        if "level" in opts:
            level = cp.get(sectname, "level")
            try:
                h.setLevel(logging._levelNames[level])
            except AttributeError:
                h.setLevel(logging._nameToLevel[level])
        if len(fmt):
            h.setFormatter(formatters[fmt])
        if issubclass(klass, logging.handlers.MemoryHandler):
            if "target" in opts:
                target = cp.get(sectname, "target")
            else:
                target = ""
            if len(target):
                fixups.append((h, target))
        handlers[hand] = h

    for h, t in fixups:
        h.setTarget(handlers[t])
    return handlers