Python logging.addLevelName() Examples

The following are 30 code examples of logging.addLevelName(). 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: __init__.py    From dwave-hybrid with Apache License 2.0 10 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 #2
Source File: customlogger.py    From pyperform with MIT License 7 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 #3
Source File: standalone.py    From pywebsocket with 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 #4
Source File: output.py    From gallery-dl with 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
Source File: __init__.py    From rhinobot_heroku with 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 #6
Source File: snapraid-runner.py    From snapraid-runner with MIT License 6 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) 
Example #7
Source File: logging.py    From eth-utils with MIT License 5 votes vote down vote up
def setup_DEBUG2_logging() -> None:
    """
    Installs the `DEBUG2` level logging levels to the main logging module.
    """
    if not hasattr(logging, "DEBUG2"):
        logging.addLevelName(DEBUG2_LEVEL_NUM, "DEBUG2")
        setattr(logging, "DEBUG2", DEBUG2_LEVEL_NUM)  # typing: ignore 
Example #8
Source File: hrinit.py    From hackerrank with The Unlicense 5 votes vote down vote up
def set_logging(verbose):
    """ set up a colorized logger """
    if sys.stdout.isatty():
        logging.addLevelName(logging.DEBUG, "\033[0;32m%s\033[0m" % logging.getLevelName(logging.DEBUG))
        logging.addLevelName(logging.INFO, "\033[1;33m%s\033[0m" % logging.getLevelName(logging.INFO))
        logging.addLevelName(logging.WARNING, "\033[1;35m%s\033[1;0m" % logging.getLevelName(logging.WARNING))
        logging.addLevelName(logging.ERROR, "\033[1;41m%s\033[1;0m" % logging.getLevelName(logging.ERROR))

    if verbose:
        logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.DEBUG, datefmt='%H:%M:%S')
    else:
        logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.ERROR, datefmt='%H:%M:%S') 
Example #9
Source File: shared_cli.py    From VeRyPy with MIT License 5 votes vote down vote up
def set_logger_level(level, logfile=None):
    #set the logger verbosity level
    if level>=0:            
        logging.basicConfig(format="%(levelname)s:%(message)s",
                            level=logging.DEBUG-level,
                            stream=sys.stdout)
        for lvl in range(1,10):
            logging.addLevelName(lvl, "DEBUG")

        if logfile is not None:
            fileloghandler = logging.FileHandler(logfile)
            fileloghandler.setLevel(logging.DEBUG-level)
            fileloghandler.setFormatter( logging.Formatter("%(levelname)s:%(message)s") )
            logging.getLogger('').addHandler(fileloghandler) 
Example #10
Source File: misc.py    From knxmap with GNU General Public License v3.0 5 votes vote down vote up
def setup_logger(level):
    levels = [logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG, TRACE_LOG_LEVEL]
    log_format = '[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s' if level > 2 else '%(message)s'
    logging.addLevelName(TRACE_LOG_LEVEL, 'TRACE')
    logging.Logger.trace = trace_packet
    logging.Logger.trace_incoming = trace_incoming
    logging.Logger.trace_outgoing = trace_outgoing
    logging.basicConfig(level=levels[min(level, len(levels) - 1)], format=log_format) 
Example #11
Source File: motuclient.py    From motu-client-python with GNU Lesser General Public License v3.0 5 votes vote down vote up
def initLogger():
    logging.addLevelName(utils_log.TRACE_LEVEL, 'TRACE')
    logging.config.fileConfig(  os.path.join(os.path.dirname(__file__),LOG_CFG_FILE) )
    global log
    log = logging.getLogger(__name__)

    logging.getLogger().setLevel(logging.INFO)
#===============================================================================
# The Main function
#=============================================================================== 
Example #12
Source File: quark_runtime_logging.py    From quark with Apache License 2.0 5 votes vote down vote up
def ensure_trace():
    global TRACE
    for lvl in range(1,logging.DEBUG):
        if len(logging.getLevelName(lvl).split()) == 1:
            TRACE = lvl
            break
    else:
        TRACE = 5
        logging.addLevelName(TRACE, "TRACE") 
Example #13
Source File: test_logging.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_regression_29220(self):
        """See issue #29220 for more information."""
        logging.addLevelName(logging.INFO, '')
        self.addCleanup(logging.addLevelName, logging.INFO, 'INFO')
        self.assertEqual(logging.getLevelName(logging.INFO), '')
        self.assertEqual(logging.getLevelName(logging.NOTSET), 'NOTSET')
        self.assertEqual(logging.getLevelName('NOTSET'), logging.NOTSET) 
Example #14
Source File: test_logging.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.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 #15
Source File: logging.py    From s3ql with GNU General Public License v3.0 5 votes vote down vote up
def setup_logging(options):

    # We want to be able to detect warnings and higher severities
    # in the captured test output. 'critical' has too many potential
    # false positives, so we rename this level to "FATAL".
    logging.addLevelName(logging.CRITICAL, 'FATAL')

    root_logger = logging.getLogger()
    if root_logger.handlers:
        root_logger.debug("Logging already initialized.")
        return

    stdout_handler = add_stdout_logging(options.quiet, getattr(options, 'systemd', False))
    if hasattr(options, 'log') and options.log:
        root_logger.addHandler(create_handler(options.log))
    elif options.debug and (not hasattr(options, 'log') or not options.log):
        # When we have debugging enabled but no separate log target,
        # make stdout logging more detailed.
        formatter = logging.Formatter('%(asctime)s.%(msecs)03d %(process)s %(levelname)-8s '
                                      '%(threadName)s %(name)s.%(funcName)s: %(message)s',
                                      datefmt="%Y-%m-%d %H:%M:%S")
        stdout_handler.setFormatter(formatter)
        stdout_handler.setLevel(logging.NOTSET)

    setup_excepthook()

    if options.debug:
        if 'all' in options.debug:
            root_logger.setLevel(logging.DEBUG)
        else:
            root_logger.setLevel(logging.INFO)
            for module in options.debug:
                logging.getLogger(module).setLevel(logging.DEBUG)

        logging.disable(logging.NOTSET)
    else:
        root_logger.setLevel(logging.INFO)
        logging.disable(logging.DEBUG)
    logging.captureWarnings(capture=True)

    return stdout_handler 
Example #16
Source File: custom_logger.py    From bfx-hf-strategy-py with 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")
        logging.addLevelName(self.POSITION, "POS_STATUS")
        return 
Example #17
Source File: utils.py    From satpy with GNU General Public License v3.0 5 votes vote down vote up
def get_logger(name):
    """Return logger with null handler added if needed."""
    if not hasattr(logging.Logger, 'trace'):
        logging.addLevelName(TRACE_LEVEL, 'TRACE')

        def trace(self, message, *args, **kwargs):
            if self.isEnabledFor(TRACE_LEVEL):
                # Yes, logger takes its '*args' as 'args'.
                self._log(TRACE_LEVEL, message, args, **kwargs)

        logging.Logger.trace = trace

    log = logging.getLogger(name)
    return log 
Example #18
Source File: utils.py    From IDArling with GNU General Public License v3.0 5 votes vote down vote up
def start_logging(log_path, log_name, level):
    """
    Setup the logger: add a new log level, create a logger which logs into
    the console and also into a log files located at: logs/idarling.%pid%.log.
    """
    if log_name in _loggers:
        return _loggers[log_name]

    # Add a new log level called TRACE, and more verbose that DEBUG.
    logging.TRACE = 5
    logging.addLevelName(logging.TRACE, "TRACE")
    logging.Logger.trace = lambda inst, msg, *args, **kwargs: inst.log(
        logging.TRACE, msg, *args, **kwargs
    )
    logging.trace = lambda msg, *args, **kwargs: logging.log(
        logging.TRACE, msg, *args, **kwargs
    )

    logger = logging.getLogger(log_name)
    if not isinstance(level, int):
        level = getattr(logging, level)
    logger.setLevel(level)

    # Log to the console with a first format
    stream_handler = logging.StreamHandler()
    log_format = "[%(levelname)s] %(message)s"
    formatter = logging.Formatter(fmt=log_format)
    stream_handler.setFormatter(formatter)
    logger.addHandler(stream_handler)

    # Log to the disk with a second format
    file_handler = logging.FileHandler(log_path)
    log_format = "[%(asctime)s][%(levelname)s] %(message)s"
    formatter = logging.Formatter(fmt=log_format, datefmt="%H:%M:%S")
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)

    _loggers[log_name] = logger
    return logger 
Example #19
Source File: logger.py    From nox with Apache License 2.0 5 votes vote down vote up
def __init__(self, name: str, level: int = logging.NOTSET):
        super(LoggerWithSuccessAndOutput, self).__init__(name, level)
        logging.addLevelName(SUCCESS, "SUCCESS")
        logging.addLevelName(OUTPUT, "OUTPUT") 
Example #20
Source File: __main__.py    From vergeml with 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 #21
Source File: hr_offline.py    From hackerrank with The Unlicense 5 votes vote down vote up
def set_logging(verbose):
    """ set up a colorized logger """
    if sys.stdout.isatty():
        logging.addLevelName(logging.DEBUG, "\033[0;32m%s\033[0m" % logging.getLevelName(logging.DEBUG))
        logging.addLevelName(logging.INFO, "\033[1;33m%s\033[0m" % logging.getLevelName(logging.INFO))
        logging.addLevelName(logging.WARNING, "\033[1;35m%s\033[1;0m" % logging.getLevelName(logging.WARNING))
        logging.addLevelName(logging.ERROR, "\033[1;41m%s\033[1;0m" % logging.getLevelName(logging.ERROR))

    if verbose:
        logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.DEBUG, datefmt='%H:%M:%S')
    else:
        logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.ERROR, datefmt='%H:%M:%S') 
Example #22
Source File: hr_interview.py    From hackerrank with The Unlicense 5 votes vote down vote up
def set_logging(verbose):
    """ set up a colorized logger """
    if sys.stdout.isatty():
        logging.addLevelName(logging.DEBUG, "\033[0;32m%s\033[0m" % logging.getLevelName(logging.DEBUG))
        logging.addLevelName(logging.INFO, "\033[1;33m%s\033[0m" % logging.getLevelName(logging.INFO))
        logging.addLevelName(logging.WARNING, "\033[1;35m%s\033[1;0m" % logging.getLevelName(logging.WARNING))
        logging.addLevelName(logging.ERROR, "\033[1;41m%s\033[1;0m" % logging.getLevelName(logging.ERROR))

    if verbose:
        logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.DEBUG, datefmt='%H:%M:%S')
    else:
        logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.ERROR, datefmt='%H:%M:%S') 
Example #23
Source File: hr_db.py    From hackerrank with The Unlicense 5 votes vote down vote up
def set_logging(verbose):
    """ set up a colorized logger """
    if sys.stdout.isatty():
        logging.addLevelName(logging.DEBUG, "\033[0;32m%s\033[0m" % logging.getLevelName(logging.DEBUG))
        logging.addLevelName(logging.INFO, "\033[1;33m%s\033[0m" % logging.getLevelName(logging.INFO))
        logging.addLevelName(logging.WARNING, "\033[1;35m%s\033[1;0m" % logging.getLevelName(logging.WARNING))
        logging.addLevelName(logging.ERROR, "\033[1;41m%s\033[1;0m" % logging.getLevelName(logging.ERROR))

    if verbose:
        logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.DEBUG, datefmt='%H:%M:%S')
    else:
        logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.ERROR, datefmt='%H:%M:%S') 
Example #24
Source File: mylogging.py    From ver-observer with GNU General Public License v3.0 5 votes vote down vote up
def _install_custom_levels():
    global _level_installed
    if _level_installed:
        return
    logging.addLevelName(VERBOSE, "VERBOSE")
    logging.addLevelName(TRACE, "TRACE")
    logging.addLevelName(NOISE, "NOISE")
    logging.addLevelName(LOWEST, "LOWEST") 
Example #25
Source File: soscleaner.py    From insights-core with Apache License 2.0 5 votes vote down vote up
def _start_logging(self, filename):
        #will get the logging instance going
        loglevel_config = 'logging.%s' % self.loglevel

        #i'd like the stdout to be under another logging name than 'con_out'
        console_log_level = 25  #between INFO and WARNING
        quiet = self.quiet
        logging.addLevelName(console_log_level, "CONSOLE")

        def con_out(self, message, *args, **kws):
            if not quiet:
                self._log(console_log_level, message, args, **kws)

        logging.Logger.con_out = con_out

        logging.basicConfig(filename=filename,
            level=eval(loglevel_config),
            format='%(asctime)s %(name)s %(levelname)s: %(message)s',
            datefmt = '%m-%d %H:%M:%S'
            )
        if not self.quiet: # pragma: no cover
            console = logging.StreamHandler(sys.stdout)
            formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s: %(message)s', '%m-%d %H:%M:%S')
            console.setFormatter(formatter)
            console.setLevel(console_log_level)
        self.logger = logging.getLogger(__name__)
        if not self.quiet:
            self.logger.addHandler(console) # pragma: no cover

        self.logger.con_out("Log File Created at %s" % filename) 
Example #26
Source File: client.py    From insights-core with Apache License 2.0 5 votes vote down vote up
def set_up_logging(config):
    logging.addLevelName(NETWORK, "NETWORK")
    if len(logging.root.handlers) == 0:
        logging.root.addHandler(get_console_handler(config))
        logging.root.addHandler(get_file_handler(config))
        configure_level(config)
        logger.debug("Logging initialized")


# -LEGACY- 
Example #27
Source File: test_logging.py    From ironpython3 with 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 #28
Source File: logger.py    From Packt-Publishing-Free-Learning with MIT License 5 votes vote down vote up
def get_logger(module_name, log_folder_path=os.getcwd()):
    """
        module_name just to distinguish where the logs come from
    """

    LOG_FILE_PATH = os.path.join(log_folder_path, "LOG_FILE.log")

    # adding a new logging level
    logging.SUCCESS = 19   # as ALL = 0, DEBUG = 10, INFO = 20, WARN = 30, ERROR = 40, FATAL = CRITICAL, CRITICAL = 50
    logging.addLevelName(logging.SUCCESS, 'SUCCESS')
    logger = logging.getLogger(module_name)
    logger.success = lambda msg, *args: logger._log(logging.SUCCESS, msg, args)

    # create formatters
    console_log_formatter = logging.Formatter('[%(levelname)s] - %(message)s')
    file_log_formatter = logging.Formatter('%(asctime)s - %(name)s - [%(levelname)s] - %(message)s')

    # create file handler
    file_handler = logging.FileHandler(LOG_FILE_PATH)
    file_handler.setFormatter(file_log_formatter)
    file_handler.setLevel(logging.DEBUG)

    # create console log handler
    stream_handler = logging.StreamHandler(sys.stdout)
    stream_handler.setFormatter(console_log_formatter)
    stream_handler.setLevel(logging.SUCCESS)

    logger.setLevel(logging.SUCCESS)
    logger.addHandler(file_handler)
    logger.addHandler(stream_handler)
    return logger 
Example #29
Source File: tools.py    From syncthing-gtk with GNU General Public License v2.0 5 votes vote down vote up
def init_logging():
	"""
	Initializes logging, sets custom logging format and adds one
	logging level with name and method to call.
	"""
	logging.basicConfig(format=LOG_FORMAT)
	# Rename levels
	logging.addLevelName(10, "D")	# Debug
	logging.addLevelName(20, "I")	# Info
	logging.addLevelName(30, "W")	# Warning
	logging.addLevelName(40, "E")	# Error
	# Create additional, "verbose" level
	logging.addLevelName(15, "V")	# Verbose
	# Add 'logging.verbose' method
	def verbose(self, msg, *args, **kwargs):
		return self.log(15, msg, *args, **kwargs)
	logging.Logger.verbose = verbose
	# Wrap Logger._log in something that can handle utf-8 exceptions
	old_log = logging.Logger._log
	def _log(self, level, msg, args, exc_info=None, extra=None):
		args = tuple([
			(c if type(c) is unicode else str(c).decode("utf-8"))
			for c in args
		])
		msg = msg if type(msg) is unicode else str(msg).decode("utf-8")
		old_log(self, level, msg, args, exc_info, extra)
	logging.Logger._log = _log 
Example #30
Source File: logger.py    From artman with Apache License 2.0 5 votes vote down vote up
def __init__(self, name, level=logging.NOTSET):
        super(Logger, self).__init__(name, level)
        logging.addLevelName(OUTPUT, 'OUTPUT')
        logging.addLevelName(SUCCESS, 'SUCCESS')