Python logging.getLevelName() Examples

The following are 30 code examples for showing how to use logging.getLevelName(). 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: toolium   Author: Telefonica   File: test_driver_wrapper.py    License: Apache License 2.0 6 votes vote down vote up
def test_connect_api_from_file(driver_wrapper):
    # Mock data
    expected_driver = None

    # Change driver type to api and configure again
    root_path = os.path.dirname(os.path.realpath(__file__))
    os.environ["Config_prop_filenames"] = os.path.join(root_path, 'conf', 'api-properties.cfg')
    driver_wrapper.configure(ConfigFiles())
    del os.environ["Config_prop_filenames"]

    # Connect and check that the returned driver is None
    assert driver_wrapper.connect(maximize=False) == expected_driver  # Check that the wrapper has been configured
    assert driver_wrapper.config.get('Driver', 'type') == ''
    assert driver_wrapper.config.get('Jira', 'enabled') == 'false'
    logger = logging.getLogger('selenium.webdriver.remote.remote_connection')
    assert logging.getLevelName(logger.level) == 'DEBUG' 
Example 2
Project: toolium   Author: Telefonica   File: test_driver_wrapper_logger.py    License: Apache License 2.0 6 votes vote down vote up
def test_configure_logger_no_changes(driver_wrapper):
    # Configure logger
    os.environ["Config_log_filename"] = 'logging.conf'
    driver_wrapper.configure_logger()
    logger = logging.getLogger('selenium.webdriver.remote.remote_connection')

    # Modify property
    new_level = 'INFO'
    logger.setLevel(new_level)
    assert logging.getLevelName(logger.level) == new_level

    # Trying to configure again
    driver_wrapper.configure_logger()

    # Configuration has not been initialized
    assert logging.getLevelName(logger.level) == new_level 
Example 3
Project: pywren-ibm-cloud   Author: pywren   File: invoker.py    License: Apache License 2.0 6 votes vote down vote up
def function_invoker(event):
    if __version__ != event['pywren_version']:
        raise Exception("WRONGVERSION", "PyWren version mismatch",
                        __version__, event['pywren_version'])

    if event['log_level']:
        cloud_logging_config(event['log_level'])
    log_level = logging.getLevelName(logger.getEffectiveLevel())
    custom_env = {'PYWREN_FUNCTION': 'True',
                  'PYTHONUNBUFFERED': 'True',
                  'PYWREN_LOGLEVEL': log_level}
    os.environ.update(custom_env)
    config = event['config']
    num_invokers = event['invokers']
    invoker = FunctionInvoker(config, num_invokers, log_level)
    invoker.run(event['job_description']) 
Example 4
Project: thingsboard-gateway   Author: thingsboard   File: tb_logger.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, gateway):
        self.current_log_level = 'INFO'
        super().__init__(logging.getLevelName(self.current_log_level))
        self.setLevel(logging.getLevelName('DEBUG'))
        self.__gateway = gateway
        self.activated = False
        self.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - [%(filename)s] - %(module)s - %(lineno)d - %(message)s'))
        self.loggers = ['service',
                        'extension',
                        'converter',
                        'connector',
                        'tb_connection'
                        ]
        for logger in self.loggers:
            log = logging.getLogger(logger)
            log.addHandler(self.__gateway.main_handler)
            log.debug("Added remote handler to log %s", logger) 
Example 5
Project: mqttwarn   Author: jpmens   File: commands.py    License: Eclipse Public License 2.0 6 votes vote down vote up
def run_mqttwarn():

    # Script name (without extension) used as last resort fallback for config/logfile names
    scriptname = os.path.splitext(os.path.basename(sys.argv[0]))[0]

    # Load configuration file
    config = load_configuration(name=scriptname)

    # Setup logging
    setup_logging(config)
    logger.info("Starting {}".format(scriptname))
    logger.info("Log level is %s" % logging.getLevelName(logger.getEffectiveLevel()))

    # Handle signals
    signal.signal(signal.SIGTERM, cleanup)
    signal.signal(signal.SIGINT, cleanup)

    # Bootstrap mqttwarn.core
    bootstrap(config=config, scriptname=scriptname)

    # Connect to broker and start listening
    connect() 
Example 6
Project: covimerage   Author: Vimjas   File: test_logging.py    License: MIT License 6 votes vote down vote up
def test_loglevel_default(default, mocker, runner):
    from covimerage import cli
    from covimerage.logger import logger

    if default:
        mocker.patch.object(logger, 'level', getattr(logging, default))
    else:
        default = 'INFO'
    reload(cli)

    result = runner.invoke(cli.main, ['-h'])

    assert logging.getLevelName(logger.level) == default
    lines = result.output.splitlines()
    assert lines, result
    idx = lines.index('  -l, --loglevel [error|warning|info|debug]')
    indent = ' ' * 34
    assert lines[idx+1:idx+3] == [
        indent + 'Set logging level explicitly (overrides',
        indent + u'-v/-q).  [default:\xa0%s]' % (default.lower(),),
    ]
    assert result.exit_code == 0 
Example 7
Project: pyquarkchain   Author: QuarkChain   File: slogging.py    License: MIT License 6 votes vote down vote up
def get_configuration():
    """
    get a configuration (snapshot) that can be used to call configure
    snapshot = get_configuration()
    configure(**snapshot)
    """
    root = getLogger()
    name_levels = [('', logging.getLevelName(root.level))]
    name_levels.extend(
        (name, logging.getLevelName(logger.level))
        for name, logger
        in root.manager.loggerDict.items()
        if hasattr(logger, 'level')
    )

    config_string = ','.join('%s:%s' % x for x in name_levels)

    return dict(config_string=config_string, log_json=SLogger.manager.log_json) 
Example 8
Project: python-netsurv   Author: sofia-netsurv   File: logging.py    License: MIT License 6 votes vote down vote up
def __init__(self, terminalwriter, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._original_fmt = self._style._fmt
        self._level_to_fmt_mapping = {}

        levelname_fmt_match = self.LEVELNAME_FMT_REGEX.search(self._fmt)
        if not levelname_fmt_match:
            return
        levelname_fmt = levelname_fmt_match.group()

        for level, color_opts in self.LOGLEVEL_COLOROPTS.items():
            formatted_levelname = levelname_fmt % {
                "levelname": logging.getLevelName(level)
            }

            # add ANSI escape sequences around the formatted levelname
            color_kwargs = {name: True for name in color_opts}
            colorized_formatted_levelname = terminalwriter.markup(
                formatted_levelname, **color_kwargs
            )
            self._level_to_fmt_mapping[level] = self.LEVELNAME_FMT_REGEX.sub(
                colorized_formatted_levelname, self._fmt
            ) 
Example 9
Project: python-netsurv   Author: sofia-netsurv   File: logging.py    License: MIT License 6 votes vote down vote up
def __init__(self, terminalwriter, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._original_fmt = self._style._fmt
        self._level_to_fmt_mapping = {}

        levelname_fmt_match = self.LEVELNAME_FMT_REGEX.search(self._fmt)
        if not levelname_fmt_match:
            return
        levelname_fmt = levelname_fmt_match.group()

        for level, color_opts in self.LOGLEVEL_COLOROPTS.items():
            formatted_levelname = levelname_fmt % {
                "levelname": logging.getLevelName(level)
            }

            # add ANSI escape sequences around the formatted levelname
            color_kwargs = {name: True for name in color_opts}
            colorized_formatted_levelname = terminalwriter.markup(
                formatted_levelname, **color_kwargs
            )
            self._level_to_fmt_mapping[level] = self.LEVELNAME_FMT_REGEX.sub(
                colorized_formatted_levelname, self._fmt
            ) 
Example 10
Project: faces   Author: skarlekar   File: _logging.py    License: GNU General Public License v2.0 6 votes vote down vote up
def setLevel(level):
    """Set logging level for the main logger."""
    level = level.lower().strip()
    imdbpyLogger.setLevel(LEVELS.get(level, logging.NOTSET))
    imdbpyLogger.log(imdbpyLogger.level, 'set logging threshold to "%s"',
                    logging.getLevelName(imdbpyLogger.level))


#imdbpyLogger.setLevel(logging.DEBUG)


# It can be an idea to have a single function to log and warn:
#import warnings
#def log_and_warn(msg, args=None, logger=None, level=None):
#    """Log the message and issue a warning."""
#    if logger is None:
#        logger = imdbpyLogger
#    if level is None:
#        level = logging.WARNING
#    if args is None:
#        args = ()
#    #warnings.warn(msg % args, stacklevel=0)
#    logger.log(level, msg % args) 
Example 11
Project: pygogo   Author: reubano   File: test_main.py    License: MIT License 6 votes vote down vote up
def test_params_and_looping(self):
        levels = ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL")
        f = StringIO()
        going = gogo.Gogo(low_hdlr=gogo.handlers.fileobj_hdlr(f))
        logger1 = going.get_logger("area1")
        logger2 = gogo.Gogo().get_logger("area2")

        logger1_msg = "A debug message\nAn info message"
        logger1.debug("A debug message")
        logger1.info("An info %s", "message")
        f.seek(0)
        nt.assert_equal(f.read().strip(), logger1_msg)
        logger2_msg = ""

        for level in [getattr(logging, l) for l in levels]:
            name = logging.getLevelName(level)
            logger2_msg += "%s message\n" % name
            logger2.log(level, "%s %s", name, "message")
            # TODO: lookup yielding from a nose test

        nt.assert_equal(logger2_msg.strip(), sys.stdout.getvalue().strip()) 
Example 12
Project: loopchain   Author: icon-project   File: configuration.py    License: Apache License 2.0 6 votes vote down vote up
def update_logger(self, logger: logging.Logger=None):
        if logger is None:
            logger = logging.root

        self._log_level = self.log_level if isinstance(self.log_level, int) else logging.getLevelName(self.log_level)

        if logger is logging.root:
            self._log_format = self.log_format.format(
                PEER_ID=self.peer_id[:8] if self.peer_id != "RadioStation" else self.peer_id,
                CHANNEL_NAME=self.channel_name
            )

            self._update_log_output_type()
            self._update_handlers(logger)

            if self.log_color:
                self._update_log_color_set(logger)
                for handler in logger.handlers:
                    if isinstance(handler, logging.StreamHandler):
                        handler.addFilter(self._root_stream_filter)
        else:
            logger.setLevel(self._log_level)

        if self.log_monitor:
            sender.setup('loopchain', host=self.log_monitor_host, port=self.log_monitor_port) 
Example 13
Project: qiskit-aer   Author: Qiskit   File: common.py    License: Apache License 2.0 6 votes vote down vote up
def __exit__(self, exc_type, exc_value, tb):
        """
        This is a modified version of TestCase._AssertLogsContext.__exit__(...)
        """
        self.logger.handlers = self.old_handlers
        self.logger.propagate = self.old_propagate
        self.logger.setLevel(self.old_level)
        if exc_type is not None:
            # let unexpected exceptions pass through
            return False

        if self.watcher.records:
            msg = 'logs of level {} or higher triggered on {}:\n'.format(
                logging.getLevelName(self.level), self.logger.name)
            for record in self.watcher.records:
                msg += 'logger %s %s:%i: %s\n' % (record.name, record.pathname,
                                                  record.lineno,
                                                  record.getMessage())

            self._raiseFailure(msg) 
Example 14
Project: hypercorn   Author: pgjones   File: logging.py    License: MIT License 6 votes vote down vote up
def _create_logger(
    name: str, target: Union[logging.Logger, str, None], level: str, sys_default: Any
) -> logging.Logger:
    if isinstance(target, logging.Logger):
        return target
    elif target is not None:
        logger = logging.getLogger(name)
        logger.propagate = False
        logger.handlers = []
        if target == "-":
            logger.addHandler(logging.StreamHandler(sys_default))
        else:
            logger.addHandler(logging.FileHandler(target))
        logger.setLevel(logging.getLevelName(level.upper()))
        return logger
    else:
        return None 
Example 15
Project: simulator   Author: P2PSP   File: monitor.py    License: GNU General Public License v3.0 6 votes vote down vote up
def add_args(self, parser):
        parser.add_argument("-s", "--set_of_rules", default="IMS",
                            help="set of rules (defaul=\"IMS\"")
        parser.add_argument("-a", "--splitter_address", default="127.0.1.1",
                            help="Splitter address")
        parser.add_argument("-p", "--splitter_port",
                            default=Peer_DBS.splitter[1], type=int,
                            help="Splitter port (default={})"
                            .format(Peer_DBS.splitter[1]))
        parser.add_argument("-m", "--peer_port", default=0, type=int,
                            help="Monitor port (default={})".format(Peer_DBS.peer_port))
        if __debug__:
            parser.add_argument("--loglevel",
                                default=logging.ERROR,
                                help="Log level (default={})"
                                .format(logging.getLevelName(logging.ERROR)))
            logging.basicConfig(format="%(message)s - %(asctime)s - %(name)s - %(levelname)s") 
Example 16
Project: numpynet   Author: uptake   File: loggit.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setLevel(self, level_tag):
        """
        Sets the logging level
        levelStr (str) - a string describing the desired logging level
                        'INFO', 'DEBUG', 'WARNING', also 'NOTSET'
        """
        self.out.setLevel(logging.getLevelName(level_tag)) 
Example 17
Project: toolium   Author: Telefonica   File: test_driver_wrapper.py    License: Apache License 2.0 5 votes vote down vote up
def test_connect(create_driver, driver_wrapper):
    # Mock data
    expected_driver = mock.MagicMock()
    create_driver.return_value = expected_driver
    driver_wrapper.utils = mock.MagicMock()
    driver_wrapper.utils.get_remote_node.return_value = ('local', None)

    # Connect and check the returned driver
    assert driver_wrapper.connect(maximize=False) == expected_driver

    # Check that the wrapper has been configured
    assert driver_wrapper.config.get('Driver', 'type') == 'firefox'
    logger = logging.getLogger('selenium.webdriver.remote.remote_connection')
    assert logging.getLevelName(logger.level) == 'DEBUG' 
Example 18
Project: toolium   Author: Telefonica   File: test_driver_wrapper.py    License: Apache License 2.0 5 votes vote down vote up
def test_connect_api(driver_type, driver_wrapper):
    # Mock data
    expected_driver = None
    driver_wrapper.config.set('Driver', 'type', driver_type)

    # Connect and check that the returned driver is None
    assert driver_wrapper.connect(maximize=False) == expected_driver  # Check that the wrapper has been configured
    assert driver_wrapper.config.get('Driver', 'type') == driver_type
    assert driver_wrapper.config.get('Jira', 'enabled') == 'false'
    logger = logging.getLogger('selenium.webdriver.remote.remote_connection')
    assert logging.getLevelName(logger.level) == 'DEBUG' 
Example 19
Project: toolium   Author: Telefonica   File: test_driver_wrapper_logger.py    License: Apache License 2.0 5 votes vote down vote up
def test_configure_logger(driver_wrapper):
    os.environ["Config_log_filename"] = 'logging.conf'
    driver_wrapper.configure_logger()
    assert logging.getLevelName(driver_wrapper.logger.getEffectiveLevel()) == 'DEBUG' 
Example 20
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):
        """ **Syntax:** logging_level=[CRITICAL|ERROR|WARNING|INFO|DEBUG|NOTSET]

        **Description:** Sets the threshold for the logger of this command invocation. Logging messages less severe than
        `logging_level` will be ignored.

        """
        return getLevelName(self._logger.getEffectiveLevel()) 
Example 21
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):
        """ **Syntax:** logging_level=[CRITICAL|ERROR|WARNING|INFO|DEBUG|NOTSET]

        **Description:** Sets the threshold for the logger of this command invocation. Logging messages less severe than
        `logging_level` will be ignored.

        """
        return getLevelName(self._logger.getEffectiveLevel()) 
Example 22
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):
        """ **Syntax:** logging_level=[CRITICAL|ERROR|WARNING|INFO|DEBUG|NOTSET]

        **Description:** Sets the threshold for the logger of this command invocation. Logging messages less severe than
        `logging_level` will be ignored.

        """
        return getLevelName(self._logger.getEffectiveLevel()) 
Example 23
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):
        """ **Syntax:** logging_level=[CRITICAL|ERROR|WARNING|INFO|DEBUG|NOTSET]

        **Description:** Sets the threshold for the logger of this command invocation. Logging messages less severe than
        `logging_level` will be ignored.

        """
        return getLevelName(self._logger.getEffectiveLevel()) 
Example 24
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):
        """ **Syntax:** logging_level=[CRITICAL|ERROR|WARNING|INFO|DEBUG|NOTSET]

        **Description:** Sets the threshold for the logger of this command invocation. Logging messages less severe than
        `logging_level` will be ignored.

        """
        return getLevelName(self._logger.getEffectiveLevel()) 
Example 25
Project: thingsboard-gateway   Author: thingsboard   File: tb_logger.py    License: Apache License 2.0 5 votes vote down vote up
def activate(self, log_level=None):
        try:
            for logger in self.loggers:
                if log_level is not None and logging.getLevelName(log_level) is not None:
                    if logger == 'tb_connection' and log_level == 'DEBUG':
                        log = logging.getLogger(logger)
                        log.setLevel(logging.getLevelName('INFO'))
                    else:
                        log = logging.getLogger(logger)
                        self.current_log_level = log_level
                        log.setLevel(logging.getLevelName(log_level))
        except Exception as e:
            log = logging.getLogger('service')
            log.exception(e)
        self.activated = True 
Example 26
Project: python-zhmcclient   Author: zhmcclient   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def print_logger(logger):
    """
    Debug function that prints the relevant settings of a Python logger.
    """
    print("Debug: Logger %r:" % logger.name)
    print("Debug:   logger level: %s (%s)" %
          (logger.level, logging.getLevelName(logger.level)))
    if not logger.handlers:
        print("Debug:   No handlers")
    for handler in logger.handlers:
        print("Debug:   Handler %s:" % type(handler))
        print("Debug:     handler level: %s (%s)" %
              (handler.level, logging.getLevelName(handler.level)))
        format = getattr(handler.formatter, '_fmt', None)
        print("Debug:     handler format: %r" % format) 
Example 27
Project: cassandra-dtest   Author: apache   File: dtest_setup.py    License: Apache License 2.0 5 votes vote down vote up
def set_cluster_log_levels(self):
        """
        The root logger gets configured in the fixture named fixture_logging_setup.
        Based on the logging configuration options the user invoked pytest with,
        that fixture sets the root logger to that configuration. We then ensure all
        Cluster objects we work with "inherit" these logging settings (which we can
        lookup off the root logger)
        """
        if logging.root.level != 'NOTSET':
            log_level = logging.getLevelName(logging.INFO)
        else:
            log_level = logging.root.level
        self.cluster.set_log_level(log_level) 
Example 28
Project: calibre-web   Author: janeczku   File: logger.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_level_name(level):
    return logging.getLevelName(level) 
Example 29
Project: stdpopsim   Author: popsim-consortium   File: test_cli.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_logging_formatter(self):
        # unittest has its grubby mits all over logging, making it difficult
        # to test log output without using unittest.TestCase.assertLogs().
        # But assertLogs uses a hard-coded log format. So here we directly
        # construct logging.LogRecord()s for testing stdpopsim.cli.CLIFormatter.
        debug_str = "baz"
        debug_dict = dict(
                name="test_logger", pathname=__file__,
                levelno=logging.DEBUG, levelname=logging.getLevelName(logging.DEBUG),
                func=sys._getframe().f_code.co_name, lineno=sys._getframe().f_lineno,
                exc_info=None, sinfo=None, msg="%s", args=(debug_str,))
        info_str = "foo"
        info_dict = dict(
                name="test_logger", pathname=__file__,
                levelno=logging.INFO, levelname=logging.getLevelName(logging.INFO),
                func=sys._getframe().f_code.co_name, lineno=sys._getframe().f_lineno,
                exc_info=None, sinfo=None, msg="%s", args=(info_str,))
        warn_str = "bar"
        warn_dict = dict(
                name="py.warnings", pathname=__file__,
                levelno=logging.WARN, levelname=logging.getLevelName(logging.WARN),
                func=sys._getframe().f_code.co_name, lineno=sys._getframe().f_lineno,
                exc_info=None, sinfo=None, msg="%s",
                args=(f"{__file__}:564: UserWarning: {warn_str}\n  "
                      f"warnings.warn(\"{warn_str}\")\n",))
        warn_dict2 = dict(
                name="test_logger", pathname=__file__,
                levelno=logging.WARN, levelname=logging.getLevelName(logging.WARN),
                func=sys._getframe().f_code.co_name, lineno=sys._getframe().f_lineno,
                exc_info=None, sinfo=None, msg="%s",
                args=(warn_str,))

        fmt = cli.CLIFormatter()
        formatted_debug_str = fmt.format(logging.makeLogRecord(debug_dict))
        formatted_info_str = fmt.format(logging.makeLogRecord(info_dict))
        formatted_warn_str = fmt.format(logging.makeLogRecord(warn_dict))
        formatted_warn_str2 = fmt.format(logging.makeLogRecord(warn_dict2))
        self.assertEqual(formatted_debug_str, "DEBUG: " + debug_str)
        self.assertEqual(formatted_info_str, "INFO: " + info_str)
        self.assertEqual(formatted_warn_str, "WARNING: " + warn_str)
        self.assertEqual(formatted_warn_str2, warn_str) 
Example 30
Project: workload-collocation-agent   Author: intel   File: logger.py    License: Apache License 2.0 5 votes vote down vote up
def init_logging(level: str, package_name: str):
    level = level.upper()
    logging.addLevelName(TRACE, 'TRACE')
    log_colors = dict(colorlog.default_log_colors, **dict(TRACE='cyan'))

    # formatter and handler
    formatter = colorlog.ColoredFormatter(
        log_colors=log_colors,
        fmt='%(asctime)s %(log_color)s%(levelname)-8s%(reset)s'
            ' %(cyan)s{%(threadName)s} %(blue)s[%(name)s]%(reset)s %(message)s',
    )

    package_logger = logging.getLogger(package_name)
    package_logger.handlers.clear()

    # do not attache the same handler twice
    handler = logging.StreamHandler(sys.stdout)
    handler.setFormatter(formatter)

    counting_handler = CountingHandler(_module_record_counters)

    # Module scoped loggers add formatter handler and disable propagation.
    package_logger.addHandler(handler)
    package_logger.addHandler(counting_handler)
    package_logger.propagate = False  # Because we have own handler.
    package_logger.setLevel(level)

    # Inform about tracing level (because of number of metrics).
    package_logger.log(TRACE, 'Package logger trace messages enabled.')

    # Prepare main log to be used by main entry point module
    # (because you cannot create logger before initialization).
    log.debug(
        'setting level=%s for %r package', logging.getLevelName(log.getEffectiveLevel()),
        package_name
    )