Python logging.TRACE Examples

The following are 30 code examples of logging.TRACE(). 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: __init__.py    From bot with MIT License 6 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 #3
Source File: EEGsynth.py    From eegsynth with 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 #4
Source File: logger.py    From Tickeys-linux with 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 #5
Source File: cli.py    From brozzler with 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 #6
Source File: logger.py    From bazarr with 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 #7
Source File: utils.py    From dwave-cloud-client with 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 #8
Source File: __init__.py    From dwave-cloud-client with 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 #9
Source File: EEGsynth.py    From eegsynth with 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 #10
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 #11
Source File: logger.py    From Tickeys-linux with MIT License 5 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 #12
Source File: __init__.py    From seasonalbot with 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 #13
Source File: trace.py    From mautrix-python with 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 #14
Source File: browser.py    From brozzler with 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 #15
Source File: __init__.py    From brozzler with Apache License 2.0 5 votes vote down vote up
def __str__(self):
        return self.__repr__()

# monkey-patch log levels TRACE and NOTICE 
Example #16
Source File: __init__.py    From dwave-hybrid with 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 #17
Source File: core.py    From dwave-hybrid with 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 #18
Source File: profiling.py    From dwave-hybrid with 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 #19
Source File: trace_logger.py    From tcex with 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 #20
Source File: logger.py    From tcex with 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 #21
Source File: logger.py    From apprise with 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 #22
Source File: test_logger.py    From apprise with 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 #23
Source File: pykms_Misc.py    From py-kms with 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 #24
Source File: __init__.py    From brozzler with 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 #25
Source File: LoggerTool.py    From PyFlow with 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 #26
Source File: log.py    From RAFCON with 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 #27
Source File: __main__.py    From kur with 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)

############################################################################### 
Example #28
Source File: model.py    From kur with Apache License 2.0 4 votes vote down vote up
def build(self):
		""" Builds the model.
		"""

		if not self._parsed:
			logger.warning('The model has not been parsed yet. We will try to '
				'parse it without context, but this may easily fail. Make '
				'sure Model.parse() is called before Model.build().')
			self.parse(None)

		logger.debug('Enumerating the model containers.')

		# Construct the high-level network nodes.
		nodes = self.enumerate_nodes(self.root)

		logger.debug('Assembling the model dependency graph.')
		input_nodes, output_nodes, network = self.assemble_graph(nodes)

		if logger.isEnabledFor(logging.TRACE):
			queue = deque(input_nodes.values())
			while queue:
				node = queue.popleft()
				logger.trace('Assembled Node: %s', node.container.name)
				logger.trace('  Uses: %s', ', '
					.join([x.container.name for x in node.inputs]))
				logger.trace('  Used by: %s', ', '
					.join([x.container.name for x in node.outputs]))
				logger.trace('  Aliases: %s', ', '.join(node.names))
				queue.extend(node.outputs)

		logger.debug('Connecting the model graph.')
		inputs, input_aliases, outputs, output_aliases = \
			self.build_graph(input_nodes, output_nodes, network)

		logger.debug('Model inputs:  %s', ', '.join(node for node in inputs))
		logger.debug('Model outputs: %s', ', '.join(node for node in outputs))

		self.inputs = inputs
		self.outputs = outputs
		self.network = network
		self.input_aliases = input_aliases
		self.output_aliases = output_aliases
		self.key_cache = {}

		self.compiled = None

	########################################################################### 
Example #29
Source File: test_core.py    From dwave-hybrid with Apache License 2.0 4 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 #30
Source File: EEGsynth.py    From eegsynth with GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, name=None, debug=0):
        self.previous_value = {}
        self.loop_time = None

        # If using Windows,this  will cause anything sent to stdout or stderr will have ANSI color codes converted to the Windows versions
        colorama.init()

        logger = logging.getLogger(__name__)
        handler = logging.StreamHandler()
        formatter = ColoredFormatter(name)
        handler.setFormatter(formatter)
        logger.addHandler(handler)

        # add a success level
        logging.SUCCESS = logging.INFO + 5
        logging.addLevelName(logging.SUCCESS, 'SUCCESS')

        # add a trace level
        logging.TRACE = logging.DEBUG - 5
        logging.addLevelName(logging.TRACE, 'TRACE')

        # remember the logger
        self.logger = logger

        if debug==0:
            logger.setLevel(logging.SUCCESS)
        elif debug==1:
            logger.setLevel(logging.INFO)
        elif debug==2:
            logger.setLevel(logging.DEBUG)
        elif debug==3:
            logger.setLevel(logging.TRACE)

        if name == None:
            fullname = 'This software'
        else:
            fullname = 'The %s module' % (name)

        print("""
##############################################################################
# %s is part of EEGsynth, see <http://www.eegsynth.org>.
#
# Copyright (C) 2017-2020 EEGsynth project
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
##############################################################################

Press Ctrl-C to stop this module.
        """ % (fullname))