Python logging.addLevelName() Examples

The following are 30 code examples for showing how to use logging.addLevelName(). 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: pyperform   Author: lobocv   File: customlogger.py    License: MIT License 6 votes vote down vote up
def __call__(self, customlevel):
        """
        Wrap the decorated function to take care of the setting up of the custom log level.

        """
        # Add the new custom level to the list of known levels
        logging.addLevelName(self.level, self.name)

        def _wrapper(msg, *args, **kwargs):
            # Check if the currently set level allows this log level to print.
            if self.logger.isEnabledFor(level):
                _msg, _args, _kwargs = customlevel(self.logger, msg, *args, **kwargs)
                self.logger.log(level, _msg, *_args, **_kwargs)

        # Create function bindings in the logger or if using the root logger, setup the bindings to allow
        # calls to logging.mycustomlevel() much like logging.info(), logging.debug() etc.
        setattr(self.logger, self.name.lower(), _wrapper)
        if self.logger_name is None:
            setattr(logging, self.name.lower(), _wrapper)

        return customlevel 
Example 2
Project: pywebsocket   Author: googlearchive   File: standalone.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _configure_logging(options):
    logging.addLevelName(common.LOGLEVEL_FINE, 'FINE')

    logger = logging.getLogger()
    logger.setLevel(logging.getLevelName(options.log_level.upper()))
    if options.log_file:
        handler = logging.handlers.RotatingFileHandler(
                options.log_file, 'a', options.log_max, options.log_count)
    else:
        handler = logging.StreamHandler()
    formatter = logging.Formatter(
            '[%(asctime)s] [%(levelname)s] %(name)s: %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    deflate_log_level_name = logging.getLevelName(
        options.deflate_log_level.upper())
    _get_logger_from_class(util._Deflater).setLevel(
        deflate_log_level_name)
    _get_logger_from_class(util._Inflater).setLevel(
        deflate_log_level_name) 
Example 3
Project: rhinobot_heroku   Author: helionmusic   File: __init__.py    License: MIT License 6 votes vote down vote up
def _add_logger_level(levelname, level, *, func_name = None):
    """

    :type levelname: str
        The reference name of the level, e.g. DEBUG, WARNING, etc
    :type level: int
        Numeric logging level
    :type func_name: str
        The name of the logger function to log to a level, e.g. "info" for log.info(...)
    """

    func_name = func_name or levelname.lower()

    setattr(logging, levelname, level)
    logging.addLevelName(level, levelname)

    exec(_func_prototype.format(logger_func_name=func_name, levelname=levelname), logging.__dict__, locals())
    setattr(logging.Logger, func_name, eval(func_name)) 
Example 4
Project: gallery-dl   Author: mikf   File: output.py    License: GNU General Public License v2.0 6 votes vote down vote up
def initialize_logging(loglevel):
    """Setup basic logging functionality before configfiles have been loaded"""
    # convert levelnames to lowercase
    for level in (10, 20, 30, 40, 50):
        name = logging.getLevelName(level)
        logging.addLevelName(level, name.lower())

    # register custom Logging class
    logging.Logger.manager.setLoggerClass(Logger)

    # setup basic logging to stderr
    formatter = Formatter(LOG_FORMAT, LOG_FORMAT_DATE)
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    handler.setLevel(loglevel)
    root = logging.getLogger()
    root.setLevel(logging.NOTSET)
    root.addHandler(handler)

    return logging.getLogger("gallery-dl") 
Example 5
Project: vergeml   Author: mme   File: __main__.py    License: MIT License 5 votes vote down vote up
def _configure_logging(level=logging.INFO):
    logging.addLevelName(logging.DEBUG, 'Debug:')
    logging.addLevelName(logging.INFO, 'Info:')
    logging.addLevelName(logging.WARNING, 'Warning!')
    logging.addLevelName(logging.CRITICAL, 'Critical!')
    logging.addLevelName(logging.ERROR, 'Error!')

    logging.basicConfig(format='%(levelname)s %(message)s', level=logging.INFO)

    if not sys.warnoptions:
        import warnings
        warnings.simplefilter("ignore")
        # TODO hack to get rid of deprecation warning that appeared allthough filters
        # are set to ignore. Is there a more sane way?
        warnings.warn = lambda *args, **kwargs: None 
Example 6
Project: jawfish   Author: war-and-code   File: util.py    License: MIT License 5 votes vote down vote up
def get_logger():
    '''
    Returns logger used by multiprocessing
    '''
    global _logger
    import logging

    logging._acquireLock()
    try:
        if not _logger:

            _logger = logging.getLogger(LOGGER_NAME)
            _logger.propagate = 0
            logging.addLevelName(SUBDEBUG, 'SUBDEBUG')
            logging.addLevelName(SUBWARNING, 'SUBWARNING')

            # XXX multiprocessing should cleanup before logging
            if hasattr(atexit, 'unregister'):
                atexit.unregister(_exit_function)
                atexit.register(_exit_function)
            else:
                atexit._exithandlers.remove((_exit_function, (), {}))
                atexit._exithandlers.append((_exit_function, (), {}))

    finally:
        logging._releaseLock()

    return _logger 
Example 7
Project: Bowler   Author: facebookincubator   File: main.py    License: MIT License 5 votes vote down vote up
def main(ctx: click.Context, debug: bool, version: bool) -> None:
    """Safe Python code modification and refactoring."""
    if version:
        from bowler import __version__

        click.echo(f"bowler {__version__}")
        return

    if debug:
        BowlerTool.NUM_PROCESSES = 1
        BowlerTool.IN_PROCESS = True

    root = logging.getLogger()
    if not root.hasHandlers():
        logging.addLevelName(logging.DEBUG, "DBG")
        logging.addLevelName(logging.INFO, "INF")
        logging.addLevelName(logging.WARNING, "WRN")
        logging.addLevelName(logging.ERROR, "ERR")
        level = logging.DEBUG if debug else logging.WARNING
        fmt = logging.Formatter("{levelname}:{filename}:{lineno}  {message}", style="{")
        han = logging.StreamHandler(stream=sys.stderr)
        han.setFormatter(fmt)
        han.setLevel(level)
        root.setLevel(level)
        root.addHandler(han)

    if ctx.invoked_subcommand is None:
        return do(None, None) 
Example 8
Project: butian-src-domains   Author: m4yfly   File: logger.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        logging.addLevelName(VULN_LEVEL.DEBUG, '[~]')
        logging.addLevelName(VULN_LEVEL.WARNING, '[!]')
        logging.addLevelName(VULN_LEVEL.ERROR, '[-]')
        logging.addLevelName(VULN_LEVEL.INFO, '[*]')
        logging.addLevelName(VULN_LEVEL.SUCCESS, '[+]') 
Example 9
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
    ) 
Example 10
Project: Lector   Author: BasioMeusPuga   File: logger.py    License: GNU General Public License v3.0 5 votes vote down vote up
def init_logging(cli_arguments):
    # This needs a separate 'Lector' in the os.path.join because
    # application name isn't explicitly set in this module

    os.makedirs(location_prefix, exist_ok=True)

    log_level = 30  # Warning and above
    # Set log level according to command line arguments
    try:
        if cli_arguments[1] == 'debug':
            log_level = 10  # Debug and above
            print('Debug logging enabled')
            try:
                os.remove(logger_filename)  # Remove old log for clarity
            except FileNotFoundError:
                pass
    except IndexError:
        pass

    # Create logging object
    logging.basicConfig(
        filename=logger_filename,
        filemode='a',
        format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
        datefmt='%Y/%m/%d  %H:%M:%S',
        level=log_level)
    logging.addLevelName(60, 'HAMMERTIME')  ## Messages that MUST be logged

    return logging.getLogger('lector.main') 
Example 11
Project: wit   Author: sifive   File: witlogger.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, name, level=logging.NOTSET):
        super().__init__(name, level)
        # Use WitFormatter for info level
        _handler = logging.StreamHandler(sys.stdout)
        _handler.setFormatter(WitFormatter())
        logging.basicConfig(level=logging.INFO, handlers=[_handler])

        logging.addLevelName(VERBOSE, 'VERBOSE')
        logging.addLevelName(TRACE, 'TRACE')
        logging.addLevelName(SPAM, 'SPAM') 
Example 12
Project: ironpython2   Author: IronLanguages   File: test_logging.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
        BaseTest.setUp(self)
        for k, v in my_logging_levels.items():
            logging.addLevelName(k, v) 
Example 13
Project: ironpython2   Author: IronLanguages   File: util.py    License: Apache License 2.0 5 votes vote down vote up
def get_logger():
    '''
    Returns logger used by multiprocessing
    '''
    global _logger
    import logging, atexit

    logging._acquireLock()
    try:
        if not _logger:

            _logger = logging.getLogger(LOGGER_NAME)
            _logger.propagate = 0
            logging.addLevelName(SUBDEBUG, 'SUBDEBUG')
            logging.addLevelName(SUBWARNING, 'SUBWARNING')

            # XXX multiprocessing should cleanup before logging
            if hasattr(atexit, 'unregister'):
                atexit.unregister(_exit_function)
                atexit.register(_exit_function)
            else:
                atexit._exithandlers.remove((_exit_function, (), {}))
                atexit._exithandlers.append((_exit_function, (), {}))

    finally:
        logging._releaseLock()

    return _logger 
Example 14
Project: aumfor   Author: virtualrealitysystems   File: debug.py    License: GNU General Public License v3.0 5 votes vote down vote up
def setup(level = 0):
    """Sets up the global logging environment"""
    formatstr = "%(levelname)-8s: %(name)-20s: %(message)s"
    logging.basicConfig(format = formatstr)
    rootlogger = logging.getLogger('')
    rootlogger.setLevel(logging.DEBUG + 1 - level)
    for i in range(1, 9):
        logging.addLevelName(logging.DEBUG - i, "DEBUG" + str(i)) 
Example 15
Project: dwave-hybrid   Author: dwavesystems   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def _create_trace_loglevel(logging):
    "Add TRACE log level and Logger.trace() method."

    logging.TRACE = 5
    logging.addLevelName(logging.TRACE, "TRACE")

    def _trace(logger, message, *args, **kwargs):
        if logger.isEnabledFor(logging.TRACE):
            logger._log(logging.TRACE, message, args, **kwargs)

    logging.Logger.trace = _trace 
Example 16
Project: indy-plenum   Author: hyperledger   File: log.py    License: Apache License 2.0 5 votes vote down vote up
def _addTraceToLogging():
        logging.addLevelName(TRACE_LOG_LEVEL, "TRACE")

        def trace(self, message, *args, **kwargs):
            if self.isEnabledFor(TRACE_LOG_LEVEL):
                self._log(TRACE_LOG_LEVEL, message, args, **kwargs)

        logging.Logger.trace = trace 
Example 17
Project: indy-plenum   Author: hyperledger   File: log.py    License: Apache License 2.0 5 votes vote down vote up
def _addDisplayToLogging():
        logging.addLevelName(DISPLAY_LOG_LEVEL, "NOTIFICATION")

        def display(self, message, *args, **kwargs):
            if self.isEnabledFor(DISPLAY_LOG_LEVEL):
                self._log(DISPLAY_LOG_LEVEL, message, args, **kwargs)

        logging.Logger.display = display 
Example 18
def __init__(self, logger, extra=None, enable_extra_levels=False):
        """
        Initialize the adapter with a logger and a dict-like object which
        provides contextual information. This constructor signature allows
        easy stacking of LoggerAdapters, if so desired.

        The dictionary passed as the ``extra`` argument will be included in every
        message sent via the adapter.

        Example:

            You can effectively pass keyword arguments as shown in the
            following example::

                >>> adapter = Rfc5424SysLogAdapter(someLogger, dict(p1=v1, p2="v2"))

        Args:
            logger (logging.Logger):
                A Logger class instance
            extra (dict):
                A Dictionary with extra contextual information, sent with every message.
            enable_extra_levels (bool):
                Add custom log levels to the logging framework.
                Use with caution because it can conflict with other packages defining custom levels.
        """
        if enable_extra_levels and not Rfc5424SysLogAdapter._extra_levels_enabled:
            logging.addLevelName(EMERGENCY, 'EMERG')
            logging.addLevelName(EMERGENCY, 'EMERGENCY')
            logging.addLevelName(ALERT, 'ALERT')
            logging.addLevelName(NOTICE, 'NOTICE')
            Rfc5424SysLogAdapter._extra_levels_enabled = True

        if extra is not None and not isinstance(extra, dict):
            raise TypeError("Parameter extra must be a dictionary")

        super(Rfc5424SysLogAdapter, self).__init__(logger, extra or {}) 
Example 19
Project: PyEngine3D   Author: ubuntunux   File: Logger.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def addLevelName(level, levelName):
    logging.addLevelName(level, levelName)


# create and get logger 
Example 20
Project: PyEngine3D   Author: ubuntunux   File: Logger.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 21
Project: BinderFilter   Author: dxwu   File: test_logging.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        BaseTest.setUp(self)
        for k, v in my_logging_levels.items():
            logging.addLevelName(k, v) 
Example 22
Project: BinderFilter   Author: dxwu   File: util.py    License: MIT License 5 votes vote down vote up
def get_logger():
    '''
    Returns logger used by multiprocessing
    '''
    global _logger
    import logging, atexit

    logging._acquireLock()
    try:
        if not _logger:

            _logger = logging.getLogger(LOGGER_NAME)
            _logger.propagate = 0
            logging.addLevelName(SUBDEBUG, 'SUBDEBUG')
            logging.addLevelName(SUBWARNING, 'SUBWARNING')

            # XXX multiprocessing should cleanup before logging
            if hasattr(atexit, 'unregister'):
                atexit.unregister(_exit_function)
                atexit.register(_exit_function)
            else:
                atexit._exithandlers.remove((_exit_function, (), {}))
                atexit._exithandlers.append((_exit_function, (), {}))

    finally:
        logging._releaseLock()

    return _logger 
Example 23
Project: textext   Author: textext   File: requirements_check.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_logging_levels():
    level_colors, COLOR_RESET = get_levels_colors()
    for name, (level, color) in level_colors.items():
        logging.addLevelName(level, color + name + COLOR_RESET) 
Example 24
Project: oss-ftp   Author: aliyun   File: test_logging.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        BaseTest.setUp(self)
        for k, v in my_logging_levels.items():
            logging.addLevelName(k, v) 
Example 25
Project: oss-ftp   Author: aliyun   File: util.py    License: MIT License 5 votes vote down vote up
def get_logger():
    '''
    Returns logger used by multiprocessing
    '''
    global _logger
    import logging, atexit

    logging._acquireLock()
    try:
        if not _logger:

            _logger = logging.getLogger(LOGGER_NAME)
            _logger.propagate = 0
            logging.addLevelName(SUBDEBUG, 'SUBDEBUG')
            logging.addLevelName(SUBWARNING, 'SUBWARNING')

            # XXX multiprocessing should cleanup before logging
            if hasattr(atexit, 'unregister'):
                atexit.unregister(_exit_function)
                atexit.register(_exit_function)
            else:
                atexit._exithandlers.remove((_exit_function, (), {}))
                atexit._exithandlers.append((_exit_function, (), {}))

    finally:
        logging._releaseLock()

    return _logger 
Example 26
Project: ARC   Author: ReactionMechanismGenerator   File: conformers.py    License: MIT License 5 votes vote down vote up
def initialize_log(verbose=logging.INFO):
    """
    Set up a simple logger for stdout printing (not saving into as log file).

    Args:
        verbose (int, optional): Specify the amount of log text seen.
    """
    logger.setLevel(verbose)
    logger.propagate = False

    # Use custom level names for cleaner log output
    logging.addLevelName(logging.CRITICAL, 'Critical: ')
    logging.addLevelName(logging.ERROR, 'Error: ')
    logging.addLevelName(logging.WARNING, 'Warning: ')
    logging.addLevelName(logging.INFO, '')
    logging.addLevelName(logging.DEBUG, '')
    logging.addLevelName(0, '')

    # Create formatter and add to handlers
    formatter = logging.Formatter('%(levelname)s%(message)s')

    # Remove old handlers before adding ours
    while logger.handlers:
        logger.removeHandler(logger.handlers[0])

    # Create console handler; send everything to stdout rather than stderr
    ch = logging.StreamHandler(sys.stdout)
    ch.setLevel(verbose)
    ch.setFormatter(formatter)
    logger.addHandler(ch) 
Example 27
Project: bitfinex-api-py   Author: bitfinexcom   File: custom_logger.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, name, logLevel='DEBUG'):
        logging.Logger.__init__(self, name, logLevel)                
        color_formatter = Formatter(self.COLOR_FORMAT)
        console = logging.StreamHandler()
        console.setFormatter(color_formatter)
        self.addHandler(console)
        logging.addLevelName(self.TRADE, "TRADE")
        return 
Example 28
Project: fanci   Author: fanci-dga-detection   File: settings.py    License: GNU General Public License v3.0 5 votes vote down vote up
def configure_logger():
    global LOGGER_CONFIGURED, log
    if not LOGGER_CONFIGURED:

        logging.Logger.manager.loggerDict.clear()
        logging.VERBOSE = 5
        logging.addLevelName(logging.VERBOSE, 'VERBOSE')
        logging.Logger.verbose = lambda inst, msg, *args, **kwargs: inst.log(logging.VERBOSE, msg, *args, **kwargs)
        logging.verbose = lambda msg, *args, **kwargs: logging.log(logging.VERBOSE, msg, *args, **kwargs)

        log = logging.getLogger('log')
        log.setLevel(LOG_LVL)
        log_formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')

        if LOG_TO_FILE:
            file_handler = logging.FileHandler(datetime.now().strftime(LOG_ROOT + 'learning_%Y_%m_%d_%H_%M_.log'))
            file_handler.setLevel(logging.INFO)
            file_handler.setFormatter(log_formatter)
            log.addHandler(file_handler)

        console_handler = logging.StreamHandler()
        console_handler.setFormatter(log_formatter)
        log.addHandler(console_handler)
        if PRINT_TO_LOG_CONVERT:
            builtins.print = log_print
        LOGGER_CONFIGURED = True 
Example 29
Project: testplan   Author: Morgan-Stanley   File: logger.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        """
        Initialise the logger and add our custom log levels and methods to
        log at each level.
        """
        super(TestplanLogger, self).__init__(*args, **kwargs)

        # Add our custom levels. We could easily set partial functions here to
        # log at each level, but by defining these methods statically on the
        # class they can be included in the API docs.
        for level_name, level in self._CUSTOM_LEVELS.items():
            logging.addLevelName(level_name, level) 
Example 30
Project: snapraid-runner   Author: Chronial   File: snapraid-runner.py    License: MIT License 5 votes vote down vote up
def setup_logger():
    log_format = logging.Formatter(
        "%(asctime)s [%(levelname)-6.6s] %(message)s")
    root_logger = logging.getLogger()
    logging.OUTPUT = 15
    logging.addLevelName(logging.OUTPUT, "OUTPUT")
    logging.OUTERR = 25
    logging.addLevelName(logging.OUTERR, "OUTERR")
    root_logger.setLevel(logging.OUTPUT)
    console_logger = logging.StreamHandler(sys.stdout)
    console_logger.setFormatter(log_format)
    root_logger.addHandler(console_logger)

    if config["logging"]["file"]:
        max_log_size = min(config["logging"]["maxsize"], 0) * 1024
        file_logger = logging.handlers.RotatingFileHandler(
            config["logging"]["file"],
            maxBytes=max_log_size,
            backupCount=9)
        file_logger.setFormatter(log_format)
        root_logger.addHandler(file_logger)

    if config["email"]["sendon"]:
        global email_log
        email_log = StringIO()
        email_logger = logging.StreamHandler(email_log)
        email_logger.setFormatter(log_format)
        if config["email"]["short"]:
            # Don't send programm stdout in email
            email_logger.setLevel(logging.INFO)
        root_logger.addHandler(email_logger)