Python logging.getLevelName() Examples
The following are 30
code examples of logging.getLevelName().
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 also want to check out all available functions/classes of the module
logging
, or try the search function
.
Example #1
Source File: logging.py From python-netsurv with MIT License | 6 votes |
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 #2
Source File: slogging.py From pyquarkchain with MIT License | 6 votes |
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 #3
Source File: configuration.py From loopchain with Apache License 2.0 | 6 votes |
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 #4
Source File: tb_logger.py From thingsboard-gateway with Apache License 2.0 | 6 votes |
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
Source File: common.py From qiskit-aer with Apache License 2.0 | 6 votes |
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 #6
Source File: test_logging.py From covimerage with MIT License | 6 votes |
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
Source File: logging.py From python-netsurv with MIT License | 6 votes |
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 #8
Source File: commands.py From mqttwarn with Eclipse Public License 2.0 | 6 votes |
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 #9
Source File: test_main.py From pygogo with MIT License | 6 votes |
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 #10
Source File: invoker.py From pywren-ibm-cloud with Apache License 2.0 | 6 votes |
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 #11
Source File: test_driver_wrapper_logger.py From toolium with Apache License 2.0 | 6 votes |
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 #12
Source File: logging.py From hypercorn with MIT License | 6 votes |
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 #13
Source File: test_driver_wrapper.py From toolium with Apache License 2.0 | 6 votes |
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 #14
Source File: _logging.py From faces with GNU General Public License v2.0 | 6 votes |
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 #15
Source File: monitor.py From simulator with GNU General Public License v3.0 | 6 votes |
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
Source File: run_app.py From telegram-uz-bot with MIT License | 5 votes |
def get_log_level(): level = logging.getLevelName(os.environ.get('LOG_LEVEL', '').upper()) if not isinstance(level, int): level = DEFAULT_LEVEL return level
Example #17
Source File: Logger.py From PyEngine3D with BSD 2-Clause "Simplified" License | 5 votes |
def test_log(): testLogger.info("TEST START") testLogger.warning("Test warning") testLogger.error("Test error") testLogger.critical("Test critical") testLogger.info("TEST END!") CUSTOM_LOG_LEVEL = logging.DEBUG + 1 addLevelName(CUSTOM_LOG_LEVEL, "CUSTOM_LOG_LEVEL") testLogger.log(CUSTOM_LOG_LEVEL, "Custom log level test. %s" % getLevelName(CUSTOM_LOG_LEVEL)) # level test testLogger.setLevel(logging.CRITICAL) testLogger.log(CUSTOM_LOG_LEVEL, "Log level test. This message must not display.")
Example #18
Source File: logger.py From efs-backup with Apache License 2.0 | 5 votes |
def config(self, loglevel='warning'): loglevel = logging.getLevelName(loglevel.upper()) mainlogger = logging.getLogger() mainlogger.setLevel(loglevel) logfmt = '{"time_stamp": "%(asctime)s", "log_level": "%(levelname)s", "log_message": %(message)s}\n' if len(mainlogger.handlers) == 0: mainlogger.addHandler(logging.StreamHandler()) mainlogger.handlers[0].setFormatter(logging.Formatter(logfmt)) self.log = logging.LoggerAdapter(mainlogger, {})
Example #19
Source File: base.py From flyingcloud with Apache License 2.0 | 5 votes |
def read_docker_output_stream(self, namespace, generator, logger_prefix, log_level=None): log_level = log_level or logging.DEBUG logger = getattr(namespace.logger, logging.getLevelName(log_level).lower()) full_output = [] for raw_chunk in generator: try: chunk, repl_count = self.filter_stream_header(raw_chunk) decoded_chunk = chunk.decode('utf-8') except UnicodeDecodeError: decoded_chunk = chunk.decode('utf-8', 'replace') logger("Couldn't decode %s", hexdump(chunk, 64)) full_output.append(decoded_chunk) try: data = json.loads(decoded_chunk) except ValueError: data = decoded_chunk.rstrip('\r\n') logger("%s: %s", logger_prefix, data) if isinstance(data, dict) and 'error' in data: raise DockerResultError("Error: {!r}".format(data)) return '\n'.join(full_output) # See "Stream details" at https://docs.docker.com/engine/api/v1.18/ # {STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4} # STREAM_TYPE = 0 (stdin), = 1 (stdout), = 2 (stderr)
Example #20
Source File: main.py From sagemaker-python-sdk with Apache License 2.0 | 5 votes |
def configure_logging(args): """ Args: args: """ log_format = "%(asctime)s %(levelname)s %(name)s: %(message)s" log_level = logging.getLevelName(args.log_level.upper()) logging.basicConfig(format=log_format, level=log_level) logging.getLogger("botocore").setLevel(args.botocore_log_level.upper())
Example #21
Source File: ext_logging.py From deepWordBug with Apache License 2.0 | 5 votes |
def get_level(self): """Returns the current log level.""" return logging.getLevelName(self.backend.level)
Example #22
Source File: logging_manager.py From eva with Apache License 2.0 | 5 votes |
def getEffectiveLevel(self): return logging.getLevelName(self._LOG.getEffectiveLevel())
Example #23
Source File: Logger.py From PyEngine3D with BSD 2-Clause "Simplified" License | 5 votes |
def getLevelName(level): return logging.getLevelName(level)
Example #24
Source File: cli.py From isilon_hadoop_tools with MIT License | 5 votes |
def configure_logging(args): """Configure logging for command-line tools.""" logging.getLogger().setLevel(logging.getLevelName(args.log_level.upper())) if not args.quiet: console_handler = logging.StreamHandler() console_handler.setFormatter(logging.Formatter('[%(levelname)s] %(message)s')) logging.getLogger().addHandler(console_handler) if args.log_file: logfile_handler = logging.FileHandler(args.log_file) logfile_handler.setFormatter( logging.Formatter('[%(asctime)s] %(name)s [%(levelname)s] %(message)s'), ) logging.getLogger().addHandler(logfile_handler)
Example #25
Source File: test_logger.py From streamalert with Apache License 2.0 | 5 votes |
def test_get_logger_env_level(): """Shared - Get Logger, Environment Level""" level = 'DEBUG' with patch.dict(os.environ, {'LOGGER_LEVEL': level}): logger = get_logger('test') assert_equal(logging.getLevelName(logger.getEffectiveLevel()), level)
Example #26
Source File: Store.py From buttersink with GNU General Public License v3.0 | 5 votes |
def skipDryRun(logger, dryRun, level=logging.DEBUG): """ Return logging function. When logging function called, will return True if action should be skipped. Log will indicate if skipped because of dry run. """ # This is an undocumented "feature" of logging module: # logging.log() requires a numeric level # logging.getLevelName() maps names to numbers if not isinstance(level, int): level = logging.getLevelName(level) return ( functools.partial(_logDryRun, logger, level) if dryRun else functools.partial(logger.log, level) )
Example #27
Source File: ht_utils.py From hometop_HT3 with GNU General Public License v3.0 | 5 votes |
def loglevel(self, loglevel=None): """ returns the currently defined 'loglevel' as defined in logging.py. Value is set in configuration-file. """ if loglevel != None: tmp_loglevel = loglevel.upper() #check first possible parameters if tmp_loglevel in ('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'): if tmp_loglevel in ('CRITICAL'): loglevel = logging.CRITICAL if tmp_loglevel in ('ERROR'): loglevel = logging.ERROR if tmp_loglevel in ('WARNING'): loglevel = logging.WARNING if tmp_loglevel in ('INFO'): loglevel = logging.INFO if tmp_loglevel in ('DEBUG'): loglevel = logging.DEBUG self._loglevel = loglevel else: self._loglevel = logging.INFO #zs#test# print("loglevel:{0}".format(logging.getLevelName(self._loglevel))) return self._loglevel #--- class clogging end ---# ################################################
Example #28
Source File: database.py From pyArango with Apache License 2.0 | 5 votes |
def __get_logger(self, logger, log_level): if logger is None: return None return getattr(logger, logging.getLevelName(log_level).lower())
Example #29
Source File: test_logger.py From tcex with Apache License 2.0 | 5 votes |
def data(self, stage, label, data, level='info'): """Log validation data in a specific format for test case. Args: stage (str): The stage of the test phase (e.g., setup, staging, run, validation, etc) label (str): The label for the provided data. data (str): The data to log. level (str, optional): The logging level to write the event. Defaults to 'info'. """ stage = f'[{stage}]' stage_width = 25 - len(level) msg = f'{stage!s:>{stage_width}} : {label!s:<20}: {data!s:<50}' level = logging.getLevelName(level.upper()) self.log(level, msg)
Example #30
Source File: logger.py From tcex with Apache License 2.0 | 5 votes |
def log_level(level): """Return proper level from string. Args: level (str): The logging level. Default to 'debug'. """ level = level or 'debug' return logging.getLevelName(level.upper())