astra.contrib.thecannon.utils.logger

Module Contents

Classes

MyFormatter Formatter instances are used to convert a LogRecord to text.
LoggerStdout A pipe for stdout to a logger.
MyLogger This class is used to set up the logging system.

Functions

print_log_level(self, message, *args, **kws)
print_exception_formatted(type, value, tb) A custom hook for printing tracebacks with colours.
colored_formatter(record) Prints log messages with colours.
astra.contrib.thecannon.utils.logger.PRINT = 15
astra.contrib.thecannon.utils.logger.print_log_level(self, message, *args, **kws)
astra.contrib.thecannon.utils.logger._print
astra.contrib.thecannon.utils.logger.print_exception_formatted(type, value, tb)

A custom hook for printing tracebacks with colours.

astra.contrib.thecannon.utils.logger.colored_formatter(record)

Prints log messages with colours.

class astra.contrib.thecannon.utils.logger.MyFormatter(fmt='%(levelname)s - %(message)s [%(funcName)s @ %(filename)s]')

Formatter instances are used to convert a LogRecord to text.

Formatters need to know how a LogRecord is constructed. They are responsible for converting a LogRecord to (usually) a string which can be interpreted by either a human or an external system. The base Formatter allows a formatting string to be specified. If none is supplied, the the style-dependent default value, “%(message)s”, “{message}”, or “${message}”, is used.

The Formatter can be initialized with a format string which makes use of knowledge of the LogRecord attributes - e.g. the default value mentioned above makes use of the fact that the user’s message and arguments are pre- formatted into a LogRecord’s message attribute. Currently, the useful attributes in a LogRecord are described by:

%(name)s Name of the logger (logging channel) %(levelno)s Numeric logging level for the message (DEBUG, INFO,

WARNING, ERROR, CRITICAL)
%(levelname)s Text logging level for the message (“DEBUG”, “INFO”,
“WARNING”, “ERROR”, “CRITICAL”)
%(pathname)s Full pathname of the source file where the logging
call was issued (if available)

%(filename)s Filename portion of pathname %(module)s Module (name portion of filename) %(lineno)d Source line number where the logging call was issued

(if available)

%(funcName)s Function name %(created)f Time when the LogRecord was created (time.time()

return value)

%(asctime)s Textual time when the LogRecord was created %(msecs)d Millisecond portion of the creation time %(relativeCreated)d Time in milliseconds when the LogRecord was created,

relative to the time the logging module was loaded (typically at application startup time)

%(thread)d Thread ID (if available) %(threadName)s Thread name (if available) %(process)d Process ID (if available) %(message)s The result of record.getMessage(), computed just as

the record is emitted
base_fmt = %(asctime)s - %(levelname)s - %(message)s [%(funcName)s @ %(filename)s]
ansi_escape
converter
default_time_format = %Y-%m-%d %H:%M:%S
default_msec_format = %s,%03d
format(self, record)

Format the specified record as text.

The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.

formatTime(self, record, datefmt=None)

Return the creation time of the specified LogRecord as formatted text.

This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, an ISO8601-like (or RFC 3339-like) format is used. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the ‘converter’ attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the ‘converter’ attribute in the Formatter class.

formatException(self, ei)

Format and return the specified exception information as a string.

This default implementation just uses traceback.print_exception()

usesTime(self)

Check if the format uses the creation time of the record.

formatMessage(self, record)
formatStack(self, stack_info)

This method is provided as an extension point for specialized formatting of stack information.

The input data is a string as returned from a call to traceback.print_stack(), but with the last trailing newline removed.

The base implementation just returns the value passed in.

astra.contrib.thecannon.utils.logger.Logger
astra.contrib.thecannon.utils.logger.fmt
class astra.contrib.thecannon.utils.logger.LoggerStdout(level)

A pipe for stdout to a logger.

write(self, message)
flush(self)
class astra.contrib.thecannon.utils.logger.MyLogger(name, level=NOTSET)

This class is used to set up the logging system.

The main functionality added by this class over the built-in logging.Logger class is the ability to keep track of the origin of the messages, the ability to enable logging of warnings.warn calls and exceptions, and the addition of colorized output and context managers to easily capture messages to a file or list.

It is addapted from the astropy logging system.

INFO = 15
_actor
fatal
save_log(self, path)
_catch_exceptions(self, exctype, value, tb)

Catches all exceptions and logs them.

warning(self, msg, category=None, use_filters=True)

Custom logging.warning.

Behaves like the default logging.warning but accepts category and use_filters as arguments. category is the type of warning we are issuing (defaults to UserWarning). If use_filters=True, checks whether there are global filters set for the message or the warning category and behaves accordingly.

_set_defaults(self, log_level=logging.INFO, redirect_stdout=False)

Reset logger to its initial state.

start_file_logger(self, path, log_file_level=logging.DEBUG)

Start file logging.

set_level(self, level)

Sets levels for both sh and (if initialised) fh.

setLevel(self, level)

Set the logging level of this logger. level must be an int or a str.

debug(self, msg, *args, **kwargs)

Log ‘msg % args’ with severity ‘DEBUG’.

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

logger.debug(“Houston, we have a %s”, “thorny problem”, exc_info=1)

info(self, msg, *args, **kwargs)

Log ‘msg % args’ with severity ‘INFO’.

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

logger.info(“Houston, we have a %s”, “interesting problem”, exc_info=1)

warn(self, msg, *args, **kwargs)
error(self, msg, *args, **kwargs)

Log ‘msg % args’ with severity ‘ERROR’.

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

logger.error(“Houston, we have a %s”, “major problem”, exc_info=1)

exception(self, msg, *args, exc_info=True, **kwargs)

Convenience method for logging an ERROR with exception information.

critical(self, msg, *args, **kwargs)

Log ‘msg % args’ with severity ‘CRITICAL’.

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

logger.critical(“Houston, we have a %s”, “major disaster”, exc_info=1)

log(self, level, msg, *args, **kwargs)

Log ‘msg % args’ with the integer severity ‘level’.

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

logger.log(level, “We have a %s”, “mysterious problem”, exc_info=1)

findCaller(self, stack_info=False)

Find the stack frame of the caller so that we can note the source file name, line number and function name.

makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)

A factory method which can be overridden in subclasses to create specialized LogRecords.

_log(self, level, msg, args, exc_info=None, extra=None, stack_info=False)

Low-level logging routine which creates a LogRecord and then calls all the handlers of this logger to handle the record.

handle(self, record)

Call the handlers for the specified record.

This method is used for unpickled records received from a socket, as well as those created locally. Logger-level filtering is applied.

addHandler(self, hdlr)

Add the specified handler to this logger.

removeHandler(self, hdlr)

Remove the specified handler from this logger.

hasHandlers(self)

See if this logger has any handlers configured.

Loop through all handlers for this logger and its parents in the logger hierarchy. Return True if a handler was found, else False. Stop searching up the hierarchy whenever a logger with the “propagate” attribute set to zero is found - that will be the last logger which is checked for the existence of handlers.

callHandlers(self, record)

Pass a record to all relevant handlers.

Loop through all handlers for this logger and its parents in the logger hierarchy. If no handler was found, output a one-off error message to sys.stderr. Stop searching up the hierarchy whenever a logger with the “propagate” attribute set to zero is found - that will be the last logger whose handlers are called.

getEffectiveLevel(self)

Get the effective level for this logger.

Loop through this logger and its parents in the logger hierarchy, looking for a non-zero logging level. Return the first one found.

isEnabledFor(self, level)

Is this logger enabled for level ‘level’?

getChild(self, suffix)

Get a logger which is a descendant to this one.

This is a convenience method, such that

logging.getLogger(‘abc’).getChild(‘def.ghi’)

is the same as

logging.getLogger(‘abc.def.ghi’)

It’s useful, for example, when the parent logger is named using __name__ rather than a literal string.

__repr__(self)

Return repr(self).

addFilter(self, filter)

Add the specified filter to this handler.

removeFilter(self, filter)

Remove the specified filter from this handler.

filter(self, record)

Determine if a record is loggable by consulting all the filters.

The default is to allow the record to be logged; any filter can veto this and the record is then dropped. Returns a zero value if a record is to be dropped, else non-zero.

Changed in version 3.2: Allow filters to be just callables.

astra.contrib.thecannon.utils.logger.log