Python logging.TRACE Examples

The following are 30 code examples for showing how to use logging.TRACE(). 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: brozzler   Author: internetarchive   File: cli.py    License: Apache License 2.0 6 votes vote down vote up
def add_common_options(arg_parser, argv=None):
    argv = argv or sys.argv
    arg_parser.add_argument(
            '-q', '--quiet', dest='log_level', action='store_const',
            default=logging.INFO, const=logging.NOTICE, help='quiet logging')
    arg_parser.add_argument(
            '-v', '--verbose', dest='log_level', action='store_const',
            default=logging.INFO, const=logging.DEBUG, help=(
                'verbose logging'))
    arg_parser.add_argument(
            '--trace', dest='log_level', action='store_const',
            default=logging.INFO, const=logging.TRACE, help=(
                'very verbose logging'))
    # arg_parser.add_argument(
    #         '-s', '--silent', dest='log_level', action='store_const',
    #         default=logging.INFO, const=logging.CRITICAL)
    arg_parser.add_argument(
            '--version', action='version',
            version='brozzler %s - %s' % (
                brozzler.__version__, os.path.basename(argv[0]))) 
Example 2
Project: Tickeys-linux   Author: BillBillBillBill   File: logger.py    License: MIT License 6 votes vote down vote up
def format(self, record):
        try:
            msg = record.msg.split(':', 1)
            if len(msg) == 2:
                record.msg = '[%-12s]%s' % (msg[0], msg[1])
        except:
            pass
        levelname = record.levelname
        if record.levelno == logging.TRACE:
            levelname = 'TRACE'
            record.levelname = levelname
        if self.use_color and levelname in COLORS:
            levelname_color = (
                COLOR_SEQ % (30 + COLORS[levelname]) + levelname + RESET_SEQ)
            record.levelname = levelname_color
        return logging.Formatter.format(self, record) 
Example 3
Project: Tickeys-linux   Author: BillBillBillBill   File: logger.py    License: MIT License 6 votes vote down vote up
def format(self, record):
        try:
            msg = record.msg.split(':', 1)
            if len(msg) == 2:
                record.msg = '[%-12s]%s' % (msg[0], msg[1])
        except:
            pass
        levelname = record.levelname
        if record.levelno == logging.TRACE:
            levelname = 'TRACE'
            record.levelname = levelname
        if self.use_color and levelname in COLORS:
            levelname_color = (
                COLOR_SEQ % (30 + COLORS[levelname]) + levelname + RESET_SEQ)
            record.levelname = levelname_color
        return logging.Formatter.format(self, record) 
Example 4
Project: eegsynth   Author: eegsynth   File: EEGsynth.py    License: GNU General Public License v3.0 6 votes vote down vote up
def format(self, record):
        colors = {
            'CRITICAL': 'reverse_red',
            'ERROR': 'red',
            'WARNING': 'yellow',
            'SUCCESS': 'green',
            'INFO': 'cyan',
            'DEBUG': 'bright_grey',
            'TRACE': 'reverse_white',
        }
        color = colors.get(record.levelname, 'white')
        if self.name:
            return colored(record.levelname, color) + ': ' + self.name + ': ' + record.getMessage()
        else:
            return colored(record.levelname, color) + ': ' + record.getMessage()


################################################################################################### 
Example 5
Project: bot   Author: python-discord   File: __init__.py    License: MIT License 5 votes vote down vote up
def monkeypatch_trace(self: logging.Logger, msg: str, *args, **kwargs) -> None:
    """
    Log 'msg % args' with severity 'TRACE'.

    To pass exception information, use the keyword argument exc_info with
    a true value, e.g.

    logger.trace("Houston, we have an %s", "interesting problem", exc_info=1)
    """
    if self.isEnabledFor(TRACE_LEVEL):
        self._log(TRACE_LEVEL, msg, args, **kwargs) 
Example 6
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 7
Project: dwave-hybrid   Author: dwavesystems   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def _apply_loglevel_from_env(logger, env='DWAVE_HYBRID_LOG_LEVEL'):
    name = os.getenv(env) or os.getenv(env.upper()) or os.getenv(env.lower())
    if not name:
        return
    levels = {'trace': logging.TRACE, 'debug': logging.DEBUG, 'info': logging.INFO,
              'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL}
    requested_level = levels.get(name.lower())
    if requested_level:
        logger.setLevel(requested_level) 
Example 8
Project: dwave-hybrid   Author: dwavesystems   File: core.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, **runopts):
        super(Runnable, self).__init__()

        self.runopts = runopts

        self.timers = defaultdict(list)
        self.timeit = make_timeit(self.timers, prefix=self.name, loglevel=logging.TRACE)

        self.counters = defaultdict(int)
        self.count = make_count(self.counters, prefix=self.name, loglevel=logging.TRACE) 
Example 9
Project: dwave-hybrid   Author: dwavesystems   File: profiling.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, name=None, loglevel=logging.TRACE):
        super(trace, self).__init__(name, loglevel) 
Example 10
Project: dwave-hybrid   Author: dwavesystems   File: test_core.py    License: Apache License 2.0 5 votes vote down vote up
def test_init(self):
        self.assertTrue(hasattr(logging, 'TRACE'))
        self.assertEqual(getattr(logging, 'TRACE'), 5)

        logger = logging.getLogger(__name__)
        self.assertTrue(callable(logger.trace)) 
Example 11
Project: tcex   Author: ThreatConnect-Inc   File: trace_logger.py    License: Apache License 2.0 5 votes vote down vote up
def trace(self, msg, *args, **kwargs):
        """Set trace logging level

        Args:
            msg (str): The message to be logged.
        """
        self.log(logging.TRACE, msg, *args, **kwargs) 
Example 12
Project: tcex   Author: ThreatConnect-Inc   File: logger.py    License: Apache License 2.0 5 votes vote down vote up
def _logger(self):
        """Return the logger. The default_args property is not available in init."""
        logging.setLoggerClass(TraceLogger)
        logger = logging.getLogger(self.logger_name)
        logger.setLevel(logging.TRACE)
        return logger 
Example 13
Project: apprise   Author: caronc   File: logger.py    License: MIT License 5 votes vote down vote up
def trace(self, message, *args, **kwargs):
    """
    Verbose Debug Logging - Trace
    """
    if self.isEnabledFor(logging.TRACE):
        self._log(logging.TRACE, message, args, **kwargs) 
Example 14
Project: apprise   Author: caronc   File: test_logger.py    License: MIT License 5 votes vote down vote up
def test_apprise_logger():
    """
    API: Apprise() Logger

    """

    # Ensure we're not running in a disabled state
    logging.disable(logging.NOTSET)

    # Set our log level
    URLBase.logger.setLevel(logging.DEPRECATE + 1)

    # Deprication will definitely not trigger
    URLBase.logger.deprecate('test')

    # Verbose Debugging is not on at this point
    URLBase.logger.trace('test')

    # Set both logging entries on
    URLBase.logger.setLevel(logging.TRACE)

    # Deprication will definitely trigger
    URLBase.logger.deprecate('test')

    # Verbose Debugging will activate
    URLBase.logger.trace('test')

    # Disable Logging
    logging.disable(logging.CRITICAL) 
Example 15
Project: py-kms   Author: SystemRage   File: pykms_Misc.py    License: The Unlicense 5 votes vote down vote up
def add_logging_level(levelName, levelNum, methodName = None):
        """ Adds a new logging level to the `logging` module and the currently configured logging class.
        `levelName` becomes an attribute of the `logging` module with the value `levelNum`.
        `methodName` becomes a convenience method for both `logging` itself and the class returned by `logging.getLoggerClass()`
        (usually just `logging.Logger`). If `methodName` is not specified, `levelName.lower()` is used.

        To avoid accidental clobberings of existing attributes, this method will raise an `AttributeError` if the level name
        is already an attribute of the `logging` module or if the method name is already present .

        Example
        -------
        >>> add_logging_level('TRACE', logging.DEBUG - 5)
        >>> logging.getLogger(__name__).setLevel("TRACE")
        >>> logging.getLogger(__name__).trace('that worked')
        >>> logging.trace('so did this')
        >>> logging.TRACE
        5
        """

        if not methodName:
                methodName = levelName.lower()

        if hasattr(logging, levelName) or hasattr(logging, methodName) or hasattr(logging.getLoggerClass(), methodName):
                return

        def logForLevel(self, message, *args, **kwargs):
                if self.isEnabledFor(levelNum):
                        self._log(levelNum, message, args, **kwargs)
        def logToRoot(message, *args, **kwargs):
                logging.log(levelNum, message, *args, **kwargs)

        logging.addLevelName(levelNum, levelName)
        setattr(logging, levelName, levelNum)
        setattr(logging.getLoggerClass(), methodName, logForLevel)
        setattr(logging, methodName, logToRoot) 
Example 16
Project: brozzler   Author: internetarchive   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def __str__(self):
        return self.__repr__()

# monkey-patch log levels TRACE and NOTICE 
Example 17
Project: brozzler   Author: internetarchive   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def _logger_trace(self, msg, *args, **kwargs):
    if self.isEnabledFor(logging.TRACE):
        self._log(logging.TRACE, msg, args, **kwargs) 
Example 18
Project: brozzler   Author: internetarchive   File: browser.py    License: Apache License 2.0 5 votes vote down vote up
def send_to_chrome(self, suppress_logging=False, **kwargs):
        msg_id = next(self._command_id)
        kwargs['id'] = msg_id
        msg = json.dumps(kwargs, separators=',:')
        logging.log(
                logging.TRACE if suppress_logging else logging.DEBUG,
                'sending message to %s: %s', self.websock, msg)
        self.websock.send(msg)
        return msg_id 
Example 19
Project: mautrix-python   Author: tulir   File: trace.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def trace(self, msg, *args, **kwargs) -> None:
        self.log(TRACE, msg, *args, **kwargs) 
Example 20
Project: seasonalbot   Author: python-discord   File: __init__.py    License: MIT License 5 votes vote down vote up
def monkeypatch_trace(self: logging.Logger, msg: str, *args, **kwargs) -> None:
    """
    Log 'msg % args' with severity 'TRACE'.

    To pass exception information, use the keyword argument exc_info with a true value, e.g.
    logger.trace("Houston, we have an %s", "interesting problem", exc_info=1)
    """
    if self.isEnabledFor(logging.TRACE):
        self._log(logging.TRACE, msg, args, **kwargs) 
Example 21
Project: IDArling   Author: IDArlingTeam   File: utils.py    License: 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 22
Project: eegsynth   Author: eegsynth   File: EEGsynth.py    License: GNU General Public License v3.0 5 votes vote down vote up
def trace(self, *args):
        if len(args)==1:
            self.logger.log(logging.TRACE, *args)
        else:
            self.logger.log(logging.TRACE, " ".join(map(format, args)))

################################################################################################### 
Example 23
Project: dwave-cloud-client   Author: dwavesystems   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def _trace(logger, message, *args, **kwargs):
    if logger.isEnabledFor(logging.TRACE):
        logger._log(logging.TRACE, message, args, **kwargs) 
Example 24
Project: dwave-cloud-client   Author: dwavesystems   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def parse_loglevel(level_name, default=logging.NOTSET):
    """Resolve numeric and symbolic log level names to numeric levels."""

    try:
        level_name = str(level_name or '').strip().lower()
    except:
        return default

    # note: make sure `TRACE` level is added to `logging` before calling this
    known_levels = {
        'notset': logging.NOTSET,
        'trace': logging.TRACE,
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'warn': logging.WARNING,
        'error': logging.ERROR,
        'critical': logging.CRITICAL,
        'fatal': logging.CRITICAL
    }

    try:
        level = int(level_name)
    except ValueError:
        level = known_levels.get(level_name, default)

    return level 
Example 25
Project: bazarr   Author: morpheus65535   File: logger.py    License: GNU General Public License v3.0 5 votes vote down vote up
def trace(self, message, *args, **kwargs):
    """
    Verbose Debug Logging - Trace
    """
    if self.isEnabledFor(logging.TRACE):
        self._log(logging.TRACE, message, args, **kwargs) 
Example 26
Project: BiblioPixel   Author: ManiacalLabs   File: log.py    License: MIT License 4 votes vote down vote up
def _addLoggingLevel(levelName, levelNum, methodName=None):
    """
    Comprehensively adds a new logging level to the `logging` module and the
    currently configured logging class.

    `levelName` becomes an attribute of the `logging` module with the value
    `levelNum`. `methodName` becomes a convenience method for both `logging`
    itself and the class returned by `logging.getLoggerClass()` (usually just
    `logging.Logger`). If `methodName` is not specified, `levelName.lower()` is
    used.

    To avoid accidental clobberings of existing attributes, this method will
    raise an `AttributeError` if the level name is already an attribute of the
    `logging` module or if the method name is already present

    Example
    -------
    >>> addLoggingLevel('TRACE', logging.DEBUG - 5)
    >>> logging.getLogger(__name__).setLevel("TRACE")
    >>> logging.getLogger(__name__).trace('that worked')
    >>> logging.trace('so did this')
    >>> logging.TRACE
    5

    """
    if not methodName:
        methodName = levelName.lower()

    if hasattr(logging, levelName):
        raise AttributeError(
            '{} already defined in logging module'.format(levelName))
    if hasattr(logging, methodName):
        raise AttributeError(
            '{} already defined in logging module'.format(methodName))
    if hasattr(logging.getLoggerClass(), methodName):
        raise AttributeError(
            '{} already defined in logger class'.format(methodName))

    # This method was inspired by the answers to Stack Overflow post
    # http://stackoverflow.com/q/2183233/2988730, especially
    # http://stackoverflow.com/a/13638084/2988730
    def logForLevel(self, message, *args, **kwargs):
        if self.isEnabledFor(levelNum):
            self._log(levelNum, message, args, **kwargs)

    def logToRoot(message, *args, **kwargs):
        logging.log(levelNum, message, *args, **kwargs)

    logging.addLevelName(levelNum, levelName)
    setattr(logging, levelName, levelNum)
    setattr(logging.getLoggerClass(), methodName, logForLevel)
    setattr(logging, methodName, logToRoot) 
Example 27
Project: RAFCON   Author: DLR-RM   File: log.py    License: Eclipse Public License 1.0 4 votes vote down vote up
def add_logging_level(level_name, level_num, method_name=None):
    """Add new logging level

    Comprehensively adds a new logging level to the `logging` module and the currently configured logging class.

    `method_name` becomes a convenience method for both `logging` itself and the class returned by
    `logging.getLoggerClass()` (usually just `logging.Logger`). If `method_name` is not specified, `level_name.lower()`
    is used.

    :param str level_name: the level name
    :param int level_num: the level number/value
    :raises AttributeError: if the level
    name is already an attribute of the `logging` module or if the method name is already present

    Example
    -------
    >>> add_logging_level('TRACE', logging.DEBUG - 5)
    >>> logging.getLogger(__name__).setLevel("TRACE")
    >>> logging.getLogger(__name__).trace('that worked')
    >>> logging.trace('so did this')
    >>> logging.TRACE
    5

    """
    if not method_name:
        method_name = level_name.lower()

    if hasattr(logging, level_name):
        raise AttributeError('{} already defined in logging module'.format(level_name))
    if hasattr(logging, method_name):
        raise AttributeError('{} already defined in logging module'.format(method_name))
    if hasattr(logging.getLoggerClass(), method_name):
        raise AttributeError('{} already defined in logger class'.format(method_name))

    # This method was inspired by the answers to Stack Overflow post
    # http://stackoverflow.com/q/2183233/2988730, especially
    # http://stackoverflow.com/a/13638084/2988730
    def log_for_level(self, message, *args, **kwargs):
        if self.isEnabledFor(level_num):
            self._log(level_num, message, args, **kwargs)
    def log_to_root(message, *args, **kwargs):
        logging.log(level_num, message, *args, **kwargs)

    logging.addLevelName(level_num, level_name)
    setattr(logging, level_name, level_num)
    setattr(logging.getLoggerClass(), method_name, log_for_level)
    setattr(logging, method_name, log_to_root) 
Example 28
Project: mlbstreamer   Author: tonycpsu   File: utils.py    License: GNU General Public License v2.0 4 votes vote down vote up
def setup_logging(level=0, handlers=[], quiet_stdout=False):

    level = LOG_LEVEL_DEFAULT + level
    if level < 0 or level >= len(LOG_LEVELS):
        raise Exception("bad log level: %d" %(level))
    # add "trace" log level
    TRACE_LEVEL_NUM = 9
    logging.addLevelName(TRACE_LEVEL_NUM, "TRACE")
    logging.TRACE = TRACE_LEVEL_NUM
    def trace(self, message, *args, **kws):
        if self.isEnabledFor(TRACE_LEVEL_NUM):
            self._log(TRACE_LEVEL_NUM, message, args, **kws)
    logging.Logger.trace = trace

    if isinstance(level, str):
        level = getattr(logging, level.upper())
    else:
        level = getattr(logging, LOG_LEVELS[level].upper())

    if not isinstance(handlers, list):
        handlers = [handlers]

    logger = logging.getLogger()
    formatter = logging.Formatter(
        "%(asctime)s [%(module)16s:%(lineno)-4d] [%(levelname)8s] %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S"
    )
    logger.setLevel(level)
    outh = logging.StreamHandler(sys.stdout)
    outh.setLevel(logging.ERROR if quiet_stdout else level)

    handlers.insert(0, outh)
    # if not handlers:
    #     handlers = [logging.StreamHandler(sys.stdout)]
    for handler in handlers:
        handler.setFormatter(formatter)
        logger.addHandler(handler)

    # logger = logging.basicConfig(
    #     level=level,
    #     format="%(asctime)s [%(module)16s:%(lineno)-4d] [%(levelname)8s] %(message)s",
    #     datefmt="%Y-%m-%d %H:%M:%S"
    # )

    logging.getLogger("requests").setLevel(level+1)
    logging.getLogger("urllib3").setLevel(level+1) 
Example 29
Project: PyFlow   Author: wonderworks-software   File: LoggerTool.py    License: Apache License 2.0 4 votes vote down vote up
def addLoggingLevel(levelName, levelNum, methodName=None):
    """
    Comprehensively adds a new logging level to the `logging` module and the
    currently configured logging class.

    `levelName` becomes an attribute of the `logging` module with the value
    `levelNum`. `methodName` becomes a convenience method for both `logging`
    itself and the class returned by `logging.getLoggerClass()` (usually just
    `logging.Logger`). If `methodName` is not specified, `levelName.lower()` is
    used.

    To avoid accidental clobberings of existing attributes, this method will
    raise an `AttributeError` if the level name is already an attribute of the
    `logging` module or if the method name is already present

    Example
    -------
    >>> addLoggingLevel('TRACE', logging.DEBUG - 5)
    >>> logging.getLogger(__name__).setLevel("TRACE")
    >>> logging.getLogger(__name__).trace('that worked')
    >>> logging.trace('so did this')
    >>> logging.TRACE
    5

    """
    if not methodName:
        methodName = levelName.lower()

    if hasattr(logging, levelName):
        raise AttributeError('{} already defined in logging module'.format(levelName))
    if hasattr(logging, methodName):
        raise AttributeError('{} already defined in logging module'.format(methodName))
    if hasattr(logging.getLoggerClass(), methodName):
        raise AttributeError('{} already defined in logger class'.format(methodName))

    # This method was inspired by the answers to Stack Overflow post
    # http://stackoverflow.com/q/2183233/2988730, especially
    # http://stackoverflow.com/a/13638084/2988730
    def logForLevel(self, message, *args, **kwargs):
        if self.isEnabledFor(levelNum):
            self._log(levelNum, message, args, **kwargs)

    def logToRoot(message, *args, **kwargs):
        logging.log(levelNum, message, *args, **kwargs)

    logging.addLevelName(levelNum, levelName)
    setattr(logging, levelName, levelNum)
    setattr(logging.getLoggerClass(), methodName, logForLevel)
    setattr(logging, methodName, logToRoot) 
Example 30
Project: kur   Author: deepgram   File: __main__.py    License: Apache License 2.0 4 votes vote down vote up
def main():
	""" Entry point for the Kur command-line script.
	"""
	gotcha = False
	plugin_dir = None
	for arg in sys.argv[1:]:
		if gotcha:
			plugin_dir = arg
			break
		elif arg == '--plugin':
			gotcha = True
	plugin_dir = plugin_dir or os.environ.get('KUR_PLUGIN')
	load_plugins(plugin_dir)

	#directly reference to module to allow this to work with python -m (and work with many debuggers)
	parser, _ = kur.__main__.build_parser()
	args = parse_args(parser)

	loglevel = {
		0 : logging.WARNING,
		1 : logging.INFO,
		2 : logging.DEBUG,
		3 : logging.TRACE
	}
	config = logging.basicConfig if args.no_color else logcolor.basicConfig
	config(
		level=loglevel.get(args.verbose, logging.TRACE),
		format='{color}[%(levelname)s %(asctime)s %(name)s:%(lineno)s]{reset} '
			'%(message)s'.format(
				color='' if args.no_color else '$COLOR',
				reset='' if args.no_color else '$RESET'
			)
	)
	logging.captureWarnings(True)

	do_monitor(args)

	if args.version:
		args.func = version
	elif not hasattr(args, 'func'):
		print('Nothing to do!', file=sys.stderr)
		print('For usage information, try: kur --help', file=sys.stderr)
		print('Or visit our homepage: {}'.format(__homepage__))
		sys.exit(1)

	engine = JinjaEngine()
	setattr(args, 'engine', engine)

	sys.exit(args.func(args) or 0)

###############################################################################