desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Flush, set the target to None and lose the buffer.'
def close(self):
self.flush() self.acquire() try: self.target = None BufferingHandler.close(self) finally: self.release()
'Initialise an instance, using the passed queue.'
def __init__(self, queue):
logging.Handler.__init__(self) self.queue = queue
'Enqueue a record. The base implementation uses put_nowait. You may want to override this method if you want to use blocking, timeouts or custom queue implementations.'
def enqueue(self, record):
self.queue.put_nowait(record)
'Prepares a record for queuing. The object returned by this method is enqueued. The base implementation formats the record to merge the message and arguments, and removes unpickleable items from the record in-place. You might want to override this method if you want to convert the record to a dict or JSON string, or se...
def prepare(self, record):
self.format(record) record.msg = record.message record.args = None record.exc_info = None return record
'Emit a record. Writes the LogRecord to the queue, preparing it for pickling first.'
def emit(self, record):
try: self.enqueue(self.prepare(record)) except Exception: self.handleError(record)
'Initialize a logging record with interesting information.'
def __init__(self, name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None, **kwargs):
ct = time.time() self.name = name self.msg = msg if (args and (len(args) == 1) and isinstance(args[0], collections.Mapping) and args[0]): args = args[0] self.args = args self.levelname = getLevelName(level) self.levelno = level self.pathname = pathname try: self.filen...
'Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied arguments with the message.'
def getMessage(self):
msg = str(self.msg) if self.args: msg = (msg % self.args) return msg
'Initialize the formatter with specified format strings. Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument (if omitted, you get the ISO8601 format). Use a style parameter of \'%\', \'{\' or \'$\' to...
def __init__(self, fmt=None, datefmt=None, style='%'):
if (style not in _STYLES): raise ValueError(('Style must be one of: %s' % ','.join(_STYLES.keys()))) self._style = _STYLES[style][0](fmt) self._fmt = self._style._fmt self.datefmt = datefmt
'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)...
def formatTime(self, record, datefmt=None):
ct = self.converter(record.created) if datefmt: s = time.strftime(datefmt, ct) else: t = time.strftime(self.default_time_format, ct) s = (self.default_msec_format % (t, record.msecs)) return s
'Format and return the specified exception information as a string. This default implementation just uses traceback.print_exception()'
def formatException(self, ei):
sio = io.StringIO() tb = ei[2] traceback.print_exception(ei[0], ei[1], tb, None, sio) s = sio.getvalue() sio.close() if (s[(-1):] == '\n'): s = s[:(-1)] return s
'Check if the format uses the creation time of the record.'
def usesTime(self):
return self._style.usesTime()
'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 :func:`traceback.print_stack`, but with the last trailing newline removed. The base implementation just returns the value passed in.'
def formatStack(self, stack_info):
return stack_info
'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()...
def format(self, record):
record.message = record.getMessage() if self.usesTime(): record.asctime = self.formatTime(record, self.datefmt) s = self.formatMessage(record) if record.exc_info: if (not record.exc_text): record.exc_text = self.formatException(record.exc_info) if record.exc_text: ...
'Optionally specify a formatter which will be used to format each individual record.'
def __init__(self, linefmt=None):
if linefmt: self.linefmt = linefmt else: self.linefmt = _defaultFormatter
'Return the header string for the specified records.'
def formatHeader(self, records):
return ''
'Return the footer string for the specified records.'
def formatFooter(self, records):
return ''
'Format the specified records and return the result as a string.'
def format(self, records):
rv = '' if (len(records) > 0): rv = (rv + self.formatHeader(records)) for record in records: rv = (rv + self.linefmt.format(record)) rv = (rv + self.formatFooter(records)) return rv
'Initialize a filter. Initialize with the name of the logger which, together with its children, will have its events allowed through the filter. If no name is specified, allow every event.'
def __init__(self, name=''):
self.name = name self.nlen = len(name)
'Determine if the specified record is to be logged. Is the specified record to be logged? Returns 0 for no, nonzero for yes. If deemed appropriate, the record may be modified in-place.'
def filter(self, record):
if (self.nlen == 0): return True elif (self.name == record.name): return True elif (record.name.find(self.name, 0, self.nlen) != 0): return False return (record.name[self.nlen] == '.')
'Initialize the list of filters to be an empty list.'
def __init__(self):
self.filters = []
'Add the specified filter to this handler.'
def addFilter(self, filter):
if (not (filter in self.filters)): self.filters.append(filter)
'Remove the specified filter from this handler.'
def removeFilter(self, filter):
if (filter in self.filters): self.filters.remove(filter)
'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. .. versionchanged: 3.2 Allow filters to be just callables.'
def filter(self, record):
rv = True for f in self.filters: if hasattr(f, 'filter'): result = f.filter(record) else: result = f(record) if (not result): rv = False break return rv
'Initializes the instance - basically setting the formatter to None and the filter list to empty.'
def __init__(self, level=NOTSET):
Filterer.__init__(self) self._name = None self.level = _checkLevel(level) self.formatter = None _addHandlerRef(self) self.createLock()
'Acquire a thread lock for serializing access to the underlying I/O.'
def createLock(self):
if threading: self.lock = threading.RLock() else: self.lock = None
'Acquire the I/O thread lock.'
def acquire(self):
if self.lock: self.lock.acquire()
'Release the I/O thread lock.'
def release(self):
if self.lock: self.lock.release()
'Set the logging level of this handler. level must be an int or a str.'
def setLevel(self, level):
self.level = _checkLevel(level)
'Format the specified record. If a formatter is set, use it. Otherwise, use the default formatter for the module.'
def format(self, record):
if self.formatter: fmt = self.formatter else: fmt = _defaultFormatter return fmt.format(record)
'Do whatever it takes to actually log the specified logging record. This version is intended to be implemented by subclasses and so raises a NotImplementedError.'
def emit(self, record):
raise NotImplementedError('emit must be implemented by Handler subclasses')
'Conditionally emit the specified logging record. Emission depends on filters which may have been added to the handler. Wrap the actual emission of the record with acquisition/release of the I/O thread lock. Returns whether the filter passed the record for emission.'
def handle(self, record):
rv = self.filter(record) if rv: self.acquire() try: self.emit(record) finally: self.release() return rv
'Set the formatter for this handler.'
def setFormatter(self, fmt):
self.formatter = fmt
'Ensure all logging output has been flushed. This version does nothing and is intended to be implemented by subclasses.'
def flush(self):
pass
'Tidy up any resources used by the handler. This version removes the handler from an internal map of handlers, _handlers, which is used for handler lookup by name. Subclasses should ensure that this gets called from overridden close() methods.'
def close(self):
_acquireLock() try: if (self._name and (self._name in _handlers)): del _handlers[self._name] finally: _releaseLock()
'Handle errors which occur during an emit() call. This method should be called from handlers when an exception is encountered during an emit() call. If raiseExceptions is false, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging sys...
def handleError(self, record):
if (raiseExceptions and sys.stderr): (t, v, tb) = sys.exc_info() try: sys.stderr.write('--- Logging error ---\n') traceback.print_exception(t, v, tb, None, sys.stderr) sys.stderr.write('Call stack:\n') frame = tb.tb_frame while ...
'Initialize the handler. If stream is not specified, sys.stderr is used.'
def __init__(self, stream=None):
Handler.__init__(self) if (stream is None): stream = sys.stderr self.stream = stream
'Flushes the stream.'
def flush(self):
self.acquire() try: if (self.stream and hasattr(self.stream, 'flush')): self.stream.flush() finally: self.release()
'Emit a record. If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an \'encoding\' attribute, it is used to de...
def emit(self, record):
try: msg = self.format(record) stream = self.stream stream.write(msg) stream.write(self.terminator) self.flush() except Exception: self.handleError(record)
'Open the specified file and use it as the stream for logging.'
def __init__(self, filename, mode='a', encoding=None, delay=False):
self.baseFilename = os.path.abspath(filename) self.mode = mode self.encoding = encoding self.delay = delay if delay: Handler.__init__(self) self.stream = None else: StreamHandler.__init__(self, self._open())
'Closes the stream.'
def close(self):
self.acquire() try: if self.stream: self.flush() if hasattr(self.stream, 'close'): self.stream.close() self.stream = None StreamHandler.close(self) finally: self.release()
'Open the current base file with the (original) mode and encoding. Return the resulting stream.'
def _open(self):
return open(self.baseFilename, self.mode, encoding=self.encoding)
'Emit a record. If the stream was not opened because \'delay\' was specified in the constructor, open it before calling the superclass\'s emit.'
def emit(self, record):
if (self.stream is None): self.stream = self._open() StreamHandler.emit(self, record)
'Initialize the handler.'
def __init__(self, level=NOTSET):
Handler.__init__(self, level)
'Initialize with the specified logger being a child of this placeholder.'
def __init__(self, alogger):
self.loggerMap = {alogger: None}
'Add the specified logger as a child of this placeholder.'
def append(self, alogger):
if (alogger not in self.loggerMap): self.loggerMap[alogger] = None
'Initialize the manager with the root node of the logger hierarchy.'
def __init__(self, rootnode):
self.root = rootnode self.disable = 0 self.emittedNoHandlerWarning = False self.loggerDict = {} self.loggerClass = None self.logRecordFactory = None
'Get a logger with the specified name (channel name), creating it if it doesn\'t yet exist. This name is a dot-separated hierarchical name, such as "a", "a.b", "a.b.c" or similar. If a PlaceHolder existed for the specified name [i.e. the logger didn\'t exist but a child of it did], replace it with the created logger an...
def getLogger(self, name):
rv = None if (not isinstance(name, str)): raise TypeError('A logger name must be a string') _acquireLock() try: if (name in self.loggerDict): rv = self.loggerDict[name] if isinstance(rv, PlaceHolder): ph = rv rv = ...
'Set the class to be used when instantiating a logger with this Manager.'
def setLoggerClass(self, klass):
if (klass != Logger): if (not issubclass(klass, Logger)): raise TypeError(('logger not derived from logging.Logger: ' + klass.__name__)) self.loggerClass = klass
'Set the factory to be used when instantiating a log record with this Manager.'
def setLogRecordFactory(self, factory):
self.logRecordFactory = factory
'Ensure that there are either loggers or placeholders all the way from the specified logger to the root of the logger hierarchy.'
def _fixupParents(self, alogger):
name = alogger.name i = name.rfind('.') rv = None while ((i > 0) and (not rv)): substr = name[:i] if (substr not in self.loggerDict): self.loggerDict[substr] = PlaceHolder(alogger) else: obj = self.loggerDict[substr] if isinstance(obj, Logger):...
'Ensure that children of the placeholder ph are connected to the specified logger.'
def _fixupChildren(self, ph, alogger):
name = alogger.name namelen = len(name) for c in ph.loggerMap.keys(): if (c.parent.name[:namelen] != name): alogger.parent = c.parent c.parent = alogger
'Initialize the logger with a name and an optional level.'
def __init__(self, name, level=NOTSET):
Filterer.__init__(self) self.name = name self.level = _checkLevel(level) self.parent = None self.propagate = True self.handlers = [] self.disabled = False
'Set the logging level of this logger. level must be an int or a str.'
def setLevel(self, level):
self.level = _checkLevel(level)
'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)'
def debug(self, msg, *args, **kwargs):
if self.isEnabledFor(DEBUG): self._log(DEBUG, 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)'
def info(self, msg, *args, **kwargs):
if self.isEnabledFor(INFO): self._log(INFO, msg, args, **kwargs)
'Log \'msg % args\' with severity \'WARNING\'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1)'
def warning(self, msg, *args, **kwargs):
if self.isEnabledFor(WARNING): self._log(WARNING, 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)'
def error(self, msg, *args, **kwargs):
if self.isEnabledFor(ERROR): self._log(ERROR, msg, args, **kwargs)
'Convenience method for logging an ERROR with exception information.'
def exception(self, msg, *args, **kwargs):
kwargs['exc_info'] = True self.error(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)'
def critical(self, msg, *args, **kwargs):
if self.isEnabledFor(CRITICAL): self._log(CRITICAL, 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)'
def log(self, level, msg, *args, **kwargs):
if (not isinstance(level, int)): if raiseExceptions: raise TypeError('level must be an integer') else: return if self.isEnabledFor(level): self._log(level, msg, args, **kwargs)
'Find the stack frame of the caller so that we can note the source file name, line number and function name.'
def findCaller(self, stack_info=False):
f = currentframe() if (f is not None): f = f.f_back rv = ('(unknown file)', 0, '(unknown function)', None) while hasattr(f, 'f_code'): co = f.f_code filename = os.path.normcase(co.co_filename) if (filename == _srcfile): f = f.f_back continue ...
'A factory method which can be overridden in subclasses to create specialized LogRecords.'
def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None):
rv = _logRecordFactory(name, level, fn, lno, msg, args, exc_info, func, sinfo) if (extra is not None): for key in extra: if ((key in ['message', 'asctime']) or (key in rv.__dict__)): raise KeyError(('Attempt to overwrite %r in LogRecord' % key)) rv....
'Low-level logging routine which creates a LogRecord and then calls all the handlers of this logger to handle the record.'
def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False):
sinfo = None if _srcfile: try: (fn, lno, func, sinfo) = self.findCaller(stack_info) except ValueError: (fn, lno, func) = ('(unknown file)', 0, '(unknown function)') else: (fn, lno, func) = ('(unknown file)', 0, '(unknown function)') if exc_info...
'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.'
def handle(self, record):
if ((not self.disabled) and self.filter(record)): self.callHandlers(record)
'Add the specified handler to this logger.'
def addHandler(self, hdlr):
_acquireLock() try: if (not (hdlr in self.handlers)): self.handlers.append(hdlr) finally: _releaseLock()
'Remove the specified handler from this logger.'
def removeHandler(self, hdlr):
_acquireLock() try: if (hdlr in self.handlers): self.handlers.remove(hdlr) finally: _releaseLock()
'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 i...
def hasHandlers(self):
c = self rv = False while c: if c.handlers: rv = True break if (not c.propagate): break else: c = c.parent return rv
'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...
def callHandlers(self, record):
c = self found = 0 while c: for hdlr in c.handlers: found = (found + 1) if (record.levelno >= hdlr.level): hdlr.handle(record) if (not c.propagate): c = None else: c = c.parent if (found == 0): if lastResort:...
'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.'
def getEffectiveLevel(self):
logger = self while logger: if logger.level: return logger.level logger = logger.parent return NOTSET
'Is this logger enabled for level \'level\'?'
def isEnabledFor(self, level):
if (self.manager.disable >= level): return False return (level >= self.getEffectiveLevel())
'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.'
def getChild(self, suffix):
if (self.root is not self): suffix = '.'.join((self.name, suffix)) return self.manager.getLogger(suffix)
'Initialize the logger with the name "root".'
def __init__(self, level):
Logger.__init__(self, 'root', level)
'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. You can effectively pass keyword arguments as shown in the following example: adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2"))'
def __init__(self, logger, extra):
self.logger = logger self.extra = extra
'Process the logging message and keyword arguments passed in to a logging call to insert contextual information. You can either manipulate the message itself, the keyword args or both. Return the message and kwargs modified (or not) to suit your needs. Normally, you\'ll only need to override this one method in a Logger...
def process(self, msg, kwargs):
kwargs['extra'] = self.extra return (msg, kwargs)
'Delegate a debug call to the underlying logger.'
def debug(self, msg, *args, **kwargs):
self.log(DEBUG, msg, *args, **kwargs)
'Delegate an info call to the underlying logger.'
def info(self, msg, *args, **kwargs):
self.log(INFO, msg, *args, **kwargs)
'Delegate a warning call to the underlying logger.'
def warning(self, msg, *args, **kwargs):
self.log(WARNING, msg, *args, **kwargs)
'Delegate an error call to the underlying logger.'
def error(self, msg, *args, **kwargs):
self.log(ERROR, msg, *args, **kwargs)
'Delegate an exception call to the underlying logger.'
def exception(self, msg, *args, **kwargs):
kwargs['exc_info'] = True self.log(ERROR, msg, *args, **kwargs)
'Delegate a critical call to the underlying logger.'
def critical(self, msg, *args, **kwargs):
self.log(CRITICAL, msg, *args, **kwargs)
'Delegate a log call to the underlying logger, after adding contextual information from this adapter instance.'
def log(self, level, msg, *args, **kwargs):
if self.isEnabledFor(level): (msg, kwargs) = self.process(msg, kwargs) self.logger._log(level, msg, args, **kwargs)
'Is this logger enabled for level \'level\'?'
def isEnabledFor(self, level):
if (self.logger.manager.disable >= level): return False return (level >= self.getEffectiveLevel())
'Set the specified level on the underlying logger.'
def setLevel(self, level):
self.logger.setLevel(level)
'Get the effective level for the underlying logger.'
def getEffectiveLevel(self):
return self.logger.getEffectiveLevel()
'See if the underlying logger has any handlers.'
def hasHandlers(self):
return self.logger.hasHandlers()
'Test that a character pointer-to-pointer is correctly passed'
def test_charpp(self):
dll = CDLL(_ctypes_test.__file__) func = dll._testfunc_c_p_p func.restype = c_char_p argv = (c_char_p * 2)() argc = c_int(2) argv[0] = 'hello' argv[1] = 'world' result = func(byref(argc), argv) self.assertEqual(result, 'world')
'Write the snapshot into a file.'
def dump(self, filename):
with open(filename, 'wb') as fp: pickle.dump(self, fp, pickle.HIGHEST_PROTOCOL)
'Load a snapshot from a file.'
@staticmethod def load(filename):
with open(filename, 'rb') as fp: return pickle.load(fp)
'Create a new Snapshot instance with a filtered traces sequence, filters is a list of Filter instances. If filters is an empty list, return a new Snapshot instance with a copy of the traces.'
def filter_traces(self, filters):
if (not isinstance(filters, Iterable)): raise TypeError(('filters must be a list of filters, not %s' % type(filters).__name__)) if filters: include_filters = [] exclude_filters = [] for trace_filter in filters: if trace_filter.inclusive: ...
'Group statistics by key_type. Return a sorted list of Statistic instances.'
def statistics(self, key_type, cumulative=False):
grouped = self._group_by(key_type, cumulative) statistics = list(grouped.values()) statistics.sort(reverse=True, key=Statistic._sort_key) return statistics
'Compute the differences with an old snapshot old_snapshot. Get statistics as a sorted list of StatisticDiff instances, grouped by group_by.'
def compare_to(self, old_snapshot, key_type, cumulative=False):
new_group = self._group_by(key_type, cumulative) old_group = old_snapshot._group_by(key_type, cumulative) statistics = _compare_grouped_stats(old_group, new_group) statistics.sort(reverse=True, key=StatisticDiff._sort_key) return statistics
'real_value, coded_value = value_decode(STRING) Called prior to setting a cookie\'s value from the network representation. The VALUE is the value read from HTTP header. Override this function to modify the behavior of cookies.'
def value_decode(self, val):
return (val, val)
'real_value, coded_value = value_encode(VALUE) Called prior to setting a cookie\'s value from the dictionary representation. The VALUE is the value being assigned. Override this function to modify the behavior of cookies.'
def value_encode(self, val):
strval = str(val) return (strval, strval)
'Private method for setting a cookie\'s value'
def __set(self, key, real_value, coded_value):
M = self.get(key, Morsel()) M.set(key, real_value, coded_value) dict.__setitem__(self, key, M)
'Dictionary style assignment.'
def __setitem__(self, key, value):
(rval, cval) = self.value_encode(value) self.__set(key, rval, cval)
'Return a string suitable for HTTP.'
def output(self, attrs=None, header='Set-Cookie:', sep='\r\n'):
result = [] items = sorted(self.items()) for (key, value) in items: result.append(value.output(attrs, header)) return sep.join(result)
'Return a string suitable for JavaScript.'
def js_output(self, attrs=None):
result = [] items = sorted(self.items()) for (key, value) in items: result.append(value.js_output(attrs)) return _nulljoin(result)
'Load cookies from a string (presumably HTTP_COOKIE) or from a dictionary. Loading cookies from a dictionary \'d\' is equivalent to calling: map(Cookie.__setitem__, d.keys(), d.values())'
def load(self, rawdata):
if isinstance(rawdata, str): self.__parse_string(rawdata) else: for (key, value) in rawdata.items(): self[key] = value return
'Override server_bind to store the server name.'
def server_bind(self):
socketserver.TCPServer.server_bind(self) (host, port) = self.socket.getsockname()[:2] self.server_name = socket.getfqdn(host) self.server_port = port
'Parse a request (internal). The request should be stored in self.raw_requestline; the results are in self.command, self.path, self.request_version and self.headers. Return True for success, False for failure; on failure, an error is sent back.'
def parse_request(self):
self.command = None self.request_version = version = self.default_request_version self.close_connection = 1 requestline = str(self.raw_requestline, 'iso-8859-1') requestline = requestline.rstrip('\r\n') self.requestline = requestline words = requestline.split() if (len(words) == 3): ...