desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Constructor. The optional locals argument will be passed to the InteractiveInterpreter base class. The optional filename argument should specify the (file)name of the input stream; it will show up in tracebacks.'
def __init__(self, locals=None, filename='<console>'):
InteractiveInterpreter.__init__(self, locals) self.filename = filename self.resetbuffer()
'Reset the input buffer.'
def resetbuffer(self):
self.buffer = []
'Closely emulate the interactive Python console. The optional banner argument specifies the banner to print before the first interaction; by default it prints a banner similar to the one printed by the real Python interpreter, followed by the current class name in parentheses (so as not to confuse this with the real in...
def interact(self, banner=None):
try: sys.ps1 except AttributeError: sys.ps1 = '>>> ' try: sys.ps2 except AttributeError: sys.ps2 = '... ' cprt = 'Type "help", "copyright", "credits" or "license" for more information.' if (banner is None): self.write(('Python...
'Push a line to the interpreter. The line should not have a trailing newline; it may have internal newlines. The line is appended to a buffer and the interpreter\'s runsource() method is called with the concatenated contents of the buffer as source. If this indicates that the command was executed or invalid, the buff...
def push(self, line):
self.buffer.append(line) source = '\n'.join(self.buffer) more = self.runsource(source, self.filename) if (not more): self.resetbuffer() return more
'Write a prompt and read a line. The returned line does not include the trailing newline. When the user enters the EOF key sequence, EOFError is raised. The base implementation uses the built-in function input(); a subclass may replace this with a different implementation.'
def raw_input(self, prompt=''):
return input(prompt)
'Resolve strings to objects using standard import and attribute syntax.'
def resolve(self, s):
name = s.split('.') used = name.pop(0) try: found = self.importer(used) for frag in name: used += ('.' + frag) try: found = getattr(found, frag) except AttributeError: self.importer(used) found = getattr(foun...
'Default converter for the ext:// protocol.'
def ext_convert(self, value):
return self.resolve(value)
'Default converter for the cfg:// protocol.'
def cfg_convert(self, value):
rest = value m = self.WORD_PATTERN.match(rest) if (m is None): raise ValueError(('Unable to convert %r' % value)) else: rest = rest[m.end():] d = self.config[m.groups()[0]] while rest: m = self.DOT_PATTERN.match(rest) if m: ...
'Convert values to an appropriate type. dicts, lists and tuples are replaced by their converting alternatives. Strings are checked to see if they have a conversion format and are converted if they do.'
def convert(self, value):
if ((not isinstance(value, ConvertingDict)) and isinstance(value, dict)): value = ConvertingDict(value) value.configurator = self elif ((not isinstance(value, ConvertingList)) and isinstance(value, list)): value = ConvertingList(value) value.configurator = self elif ((not isi...
'Configure an object with a user-supplied factory.'
def configure_custom(self, config):
c = config.pop('()') if (not callable(c)): c = self.resolve(c) props = config.pop('.', None) kwargs = dict([(k, config[k]) for k in config if valid_ident(k)]) result = c(**kwargs) if props: for (name, value) in props.items(): setattr(result, name, value) return re...
'Utility function which converts lists to tuples.'
def as_tuple(self, value):
if isinstance(value, list): value = tuple(value) return value
'Do the configuration.'
def configure(self):
config = self.config if ('version' not in config): raise ValueError("dictionary doesn't specify a version") if (config['version'] != 1): raise ValueError(('Unsupported version: %s' % config['version'])) incremental = config.pop('incremental', False) EMPTY_DICT = {} ...
'Configure a formatter from a dictionary.'
def configure_formatter(self, config):
if ('()' in config): factory = config['()'] try: result = self.configure_custom(config) except TypeError as te: if ("'format'" not in str(te)): raise config['fmt'] = config.pop('format') config['()'] = factory result...
'Configure a filter from a dictionary.'
def configure_filter(self, config):
if ('()' in config): result = self.configure_custom(config) else: name = config.get('name', '') result = logging.Filter(name) return result
'Add filters to a filterer from a list of names.'
def add_filters(self, filterer, filters):
for f in filters: try: filterer.addFilter(self.config['filters'][f]) except Exception as e: raise ValueError(('Unable to add filter %r: %s' % (f, e)))
'Configure a handler from a dictionary.'
def configure_handler(self, config):
config_copy = dict(config) formatter = config.pop('formatter', None) if formatter: try: formatter = self.config['formatters'][formatter] except Exception as e: raise ValueError(('Unable to set formatter %r: %s' % (formatter, e))) level = config.pop(...
'Add handlers to a logger from a list of names.'
def add_handlers(self, logger, handlers):
for h in handlers: try: logger.addHandler(self.config['handlers'][h]) except Exception as e: raise ValueError(('Unable to add handler %r: %s' % (h, e)))
'Perform configuration which is common to root and non-root loggers.'
def common_logger_config(self, logger, config, incremental=False):
level = config.get('level', None) if (level is not None): logger.setLevel(logging._checkLevel(level)) if (not incremental): for h in logger.handlers[:]: logger.removeHandler(h) handlers = config.get('handlers', None) if handlers: self.add_handlers(logg...
'Configure a non-root logger from a dictionary.'
def configure_logger(self, name, config, incremental=False):
logger = logging.getLogger(name) self.common_logger_config(logger, config, incremental) propagate = config.get('propagate', None) if (propagate is not None): logger.propagate = propagate
'Configure a root logger from a dictionary.'
def configure_root(self, config, incremental=False):
root = logging.getLogger() self.common_logger_config(root, config, incremental)
'Use the specified filename for streamed logging'
def __init__(self, filename, mode, encoding=None, delay=False):
logging.FileHandler.__init__(self, filename, mode, encoding, delay) self.mode = mode self.encoding = encoding self.namer = None self.rotator = None
'Emit a record. Output the record to the file, catering for rollover as described in doRollover().'
def emit(self, record):
try: if self.shouldRollover(record): self.doRollover() logging.FileHandler.emit(self, record) except Exception: self.handleError(record)
'Modify the filename of a log file when rotating. This is provided so that a custom filename can be provided. The default implementation calls the \'namer\' attribute of the handler, if it\'s callable, passing the default name to it. If the attribute isn\'t callable (the default is None), the name is returned unchanged...
def rotation_filename(self, default_name):
if (not callable(self.namer)): result = default_name else: result = self.namer(default_name) return result
'When rotating, rotate the current log. The default implementation calls the \'rotator\' attribute of the handler, if it\'s callable, passing the source and dest arguments to it. If the attribute isn\'t callable (the default is None), the source is simply renamed to the destination. :param source: The source filename. ...
def rotate(self, source, dest):
if (not callable(self.rotator)): if os.path.exists(source): os.rename(source, dest) else: self.rotator(source, dest)
'Open the specified file and use it as the stream for logging. By default, the file grows indefinitely. You can specify particular values of maxBytes and backupCount to allow the file to rollover at a predetermined size. Rollover occurs whenever the current log file is nearly maxBytes in length. If backupCount is >= 1,...
def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False):
if (maxBytes > 0): mode = 'a' BaseRotatingHandler.__init__(self, filename, mode, encoding, delay) self.maxBytes = maxBytes self.backupCount = backupCount
'Do a rollover, as described in __init__().'
def doRollover(self):
if self.stream: self.stream.close() self.stream = None if (self.backupCount > 0): for i in range((self.backupCount - 1), 0, (-1)): sfn = self.rotation_filename(('%s.%d' % (self.baseFilename, i))) dfn = self.rotation_filename(('%s.%d' % (self.baseFilename, (i + 1))...
'Determine if rollover should occur. Basically, see if the supplied record would cause the file to exceed the size limit we have.'
def shouldRollover(self, record):
if (self.stream is None): self.stream = self._open() if (self.maxBytes > 0): msg = ('%s\n' % self.format(record)) self.stream.seek(0, 2) if ((self.stream.tell() + len(msg)) >= self.maxBytes): return 1 return 0
'Work out the rollover time based on the specified time.'
def computeRollover(self, currentTime):
result = (currentTime + self.interval) if ((self.when == 'MIDNIGHT') or self.when.startswith('W')): if self.utc: t = time.gmtime(currentTime) else: t = time.localtime(currentTime) currentHour = t[3] currentMinute = t[4] currentSecond = t[5] ...
'Determine if rollover should occur. record is not used, as we are just comparing times, but it is needed so the method signatures are the same'
def shouldRollover(self, record):
t = int(time.time()) if (t >= self.rolloverAt): return 1 return 0
'Determine the files to delete when rolling over. More specific than the earlier method, which just used glob.glob().'
def getFilesToDelete(self):
(dirName, baseName) = os.path.split(self.baseFilename) fileNames = os.listdir(dirName) result = [] prefix = (baseName + '.') plen = len(prefix) for fileName in fileNames: if (fileName[:plen] == prefix): suffix = fileName[plen:] if self.extMatch.match(suffix): ...
'do a rollover; in this case, a date/time stamp is appended to the filename when the rollover happens. However, you want the file to be named for the start of the interval, not the current time. If there is a backup count, then we have to get a list of matching filenames, sort them and remove the one with the oldest ...
def doRollover(self):
if self.stream: self.stream.close() self.stream = None currentTime = int(time.time()) dstNow = time.localtime(currentTime)[(-1)] t = (self.rolloverAt - self.interval) if self.utc: timeTuple = time.gmtime(t) else: timeTuple = time.localtime(t) dstThen = tim...
'Emit a record. First check if the underlying file has changed, and if it has, close the old stream and reopen the file to get the current stream.'
def emit(self, record):
try: sres = os.stat(self.baseFilename) except FileNotFoundError: sres = None if ((not sres) or (sres[ST_DEV] != self.dev) or (sres[ST_INO] != self.ino)): if (self.stream is not None): self.stream.flush() self.stream.close() self.stream = None ...
'Initializes the handler with a specific host address and port. When the attribute *closeOnError* is set to True - if a socket error occurs, the socket is silently closed and then reopened on the next logging call.'
def __init__(self, host, port):
logging.Handler.__init__(self) self.host = host self.port = port if (port is None): self.address = host else: self.address = (host, port) self.sock = None self.closeOnError = False self.retryTime = None self.retryStart = 1.0 self.retryMax = 30.0 self.retryFact...
'A factory method which allows subclasses to define the precise type of socket they want.'
def makeSocket(self, timeout=1):
if (self.port is not None): result = socket.create_connection(self.address, timeout=timeout) else: result = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) result.settimeout(timeout) try: result.connect(self.address) except OSError: result.close(...
'Try to create a socket, using an exponential backoff with a max retry time. Thanks to Robert Olson for the original patch (SF #815911) which has been slightly refactored.'
def createSocket(self):
now = time.time() if (self.retryTime is None): attempt = True else: attempt = (now >= self.retryTime) if attempt: try: self.sock = self.makeSocket() self.retryTime = None except OSError: if (self.retryTime is None): self...
'Send a pickled string to the socket. This function allows for partial sends which can happen when the network is busy.'
def send(self, s):
if (self.sock is None): self.createSocket() if self.sock: try: self.sock.sendall(s) except OSError: self.sock.close() self.sock = None
'Pickles the record in binary format with a length prefix, and returns it ready for transmission across the socket.'
def makePickle(self, record):
ei = record.exc_info if ei: dummy = self.format(record) d = dict(record.__dict__) d['msg'] = record.getMessage() d['args'] = None d['exc_info'] = None s = pickle.dumps(d, 1) slen = struct.pack('>L', len(s)) return (slen + s)
'Handle an error during logging. An error has occurred during logging. Most likely cause - connection lost. Close the socket so that we can retry on the next event.'
def handleError(self, record):
if (self.closeOnError and self.sock): self.sock.close() self.sock = None else: logging.Handler.handleError(self, record)
'Emit a record. Pickles the record and writes it to the socket in binary format. If there is an error with the socket, silently drop the packet. If there was a problem with the socket, re-establishes the socket.'
def emit(self, record):
try: s = self.makePickle(record) self.send(s) except Exception: self.handleError(record)
'Closes the socket.'
def close(self):
self.acquire() try: if self.sock: self.sock.close() self.sock = None logging.Handler.close(self) finally: self.release()
'Initializes the handler with a specific host address and port.'
def __init__(self, host, port):
SocketHandler.__init__(self, host, port) self.closeOnError = False
'The factory method of SocketHandler is here overridden to create a UDP socket (SOCK_DGRAM).'
def makeSocket(self):
if (self.port is None): family = socket.AF_UNIX else: family = socket.AF_INET s = socket.socket(family, socket.SOCK_DGRAM) return s
'Send a pickled string to a socket. This function no longer allows for partial sends which can happen when the network is busy - UDP does not guarantee delivery and can deliver packets out of sequence.'
def send(self, s):
if (self.sock is None): self.createSocket() self.sock.sendto(s, self.address)
'Initialize a handler. If address is specified as a string, a UNIX socket is used. To log to a local syslogd, "SysLogHandler(address="/dev/log")" can be used. If facility is not specified, LOG_USER is used. If socktype is specified as socket.SOCK_DGRAM or socket.SOCK_STREAM, that specific socket type will be used. For ...
def __init__(self, address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=None):
logging.Handler.__init__(self) self.address = address self.facility = facility self.socktype = socktype if isinstance(address, str): self.unixsocket = True self._connect_unixsocket(address) else: self.unixsocket = False if (socktype is None): socktype ...
'Encode the facility and priority. You can pass in strings or integers - if strings are passed, the facility_names and priority_names mapping dictionaries are used to convert them to integers.'
def encodePriority(self, facility, priority):
if isinstance(facility, str): facility = self.facility_names[facility] if isinstance(priority, str): priority = self.priority_names[priority] return ((facility << 3) | priority)
'Closes the socket.'
def close(self):
self.acquire() try: self.socket.close() logging.Handler.close(self) finally: self.release()
'Map a logging level name to a key in the priority_names map. This is useful in two scenarios: when custom levels are being used, and in the case where you can\'t do a straightforward mapping by lowercasing the logging level name because of locale- specific issues (see SF #1524081).'
def mapPriority(self, levelName):
return self.priority_map.get(levelName, 'warning')
'Emit a record. The record is formatted, and then sent to the syslog server. If exception information is present, it is NOT sent to the server.'
def emit(self, record):
msg = self.format(record) if self.ident: msg = (self.ident + msg) if self.append_nul: msg += '\x00' prio = ('<%d>' % self.encodePriority(self.facility, self.mapPriority(record.levelname))) prio = prio.encode('utf-8') msg = msg.encode('utf-8') msg = (prio + msg) try: ...
'Initialize the handler. Initialize the instance with the from and to addresses and subject line of the email. To specify a non-standard SMTP port, use the (host, port) tuple format for the mailhost argument. To specify authentication credentials, supply a (username, password) tuple for the credentials argument. To spe...
def __init__(self, mailhost, fromaddr, toaddrs, subject, credentials=None, secure=None, timeout=5.0):
logging.Handler.__init__(self) if isinstance(mailhost, tuple): (self.mailhost, self.mailport) = mailhost else: (self.mailhost, self.mailport) = (mailhost, None) if isinstance(credentials, tuple): (self.username, self.password) = credentials else: self.username = None ...
'Determine the subject for the email. If you want to specify a subject line which is record-dependent, override this method.'
def getSubject(self, record):
return self.subject
'Emit a record. Format the record and send it to the specified addressees.'
def emit(self, record):
try: import smtplib from email.utils import formatdate port = self.mailport if (not port): port = smtplib.SMTP_PORT smtp = smtplib.SMTP(self.mailhost, port, timeout=self.timeout) msg = self.format(record) msg = ('From: %s\r\nTo: %s\r\nSubject...
'Return the message ID for the event record. If you are using your own messages, you could do this by having the msg passed to the logger being an ID rather than a formatting string. Then, in here, you could use a dictionary lookup to get the message ID. This version returns 1, which is the base message ID in win32serv...
def getMessageID(self, record):
return 1
'Return the event category for the record. Override this if you want to specify your own categories. This version returns 0.'
def getEventCategory(self, record):
return 0
'Return the event type for the record. Override this if you want to specify your own types. This version does a mapping using the handler\'s typemap attribute, which is set up in __init__() to a dictionary which contains mappings for DEBUG, INFO, WARNING, ERROR and CRITICAL. If you are using your own levels you will ei...
def getEventType(self, record):
return self.typemap.get(record.levelno, self.deftype)
'Emit a record. Determine the message ID, event category and event type. Then log the message in the NT event log.'
def emit(self, record):
if self._welu: try: id = self.getMessageID(record) cat = self.getEventCategory(record) type = self.getEventType(record) msg = self.format(record) self._welu.ReportEvent(self.appname, id, cat, type, [msg]) except Exception: self....
'Clean up this handler. You can remove the application name from the registry as a source of event log entries. However, if you do this, you will not be able to see the events as you intended in the Event Log Viewer - it needs to be able to access the registry to get the DLL name.'
def close(self):
logging.Handler.close(self)
'Initialize the instance with the host, the request URL, and the method ("GET" or "POST")'
def __init__(self, host, url, method='GET', secure=False, credentials=None):
logging.Handler.__init__(self) method = method.upper() if (method not in ['GET', 'POST']): raise ValueError('method must be GET or POST') self.host = host self.url = url self.method = method self.secure = secure self.credentials = credentials
'Default implementation of mapping the log record into a dict that is sent as the CGI data. Overwrite in your class. Contributed by Franz Glasner.'
def mapLogRecord(self, record):
return record.__dict__
'Emit a record. Send the record to the Web server as a percent-encoded dictionary'
def emit(self, record):
try: import http.client, urllib.parse host = self.host if self.secure: h = http.client.HTTPSConnection(host) else: h = http.client.HTTPConnection(host) url = self.url data = urllib.parse.urlencode(self.mapLogRecord(record)) if (self.met...
'Initialize the handler with the buffer size.'
def __init__(self, capacity):
logging.Handler.__init__(self) self.capacity = capacity self.buffer = []
'Should the handler flush its buffer? Returns true if the buffer is up to capacity. This method can be overridden to implement custom flushing strategies.'
def shouldFlush(self, record):
return (len(self.buffer) >= self.capacity)
'Emit a record. Append the record. If shouldFlush() tells us to, call flush() to process the buffer.'
def emit(self, record):
self.buffer.append(record) if self.shouldFlush(record): self.flush()
'Override to implement custom flushing behaviour. This version just zaps the buffer to empty.'
def flush(self):
self.acquire() try: self.buffer = [] finally: self.release()
'Close the handler. This version just flushes and chains to the parent class\' close().'
def close(self):
self.flush() logging.Handler.close(self)
'Initialize the handler with the buffer size, the level at which flushing should occur and an optional target. Note that without a target being set either here or via setTarget(), a MemoryHandler is no use to anyone!'
def __init__(self, capacity, flushLevel=logging.ERROR, target=None):
BufferingHandler.__init__(self, capacity) self.flushLevel = flushLevel self.target = target
'Check for buffer full or a record at the flushLevel or higher.'
def shouldFlush(self, record):
return ((len(self.buffer) >= self.capacity) or (record.levelno >= self.flushLevel))
'Set the target handler for this handler.'
def setTarget(self, target):
self.target = target
'For a MemoryHandler, flushing means just sending the buffered records to the target, if there is one. Override if you want different behaviour. The record buffer is also cleared by this operation.'
def flush(self):
self.acquire() try: if self.target: for record in self.buffer: self.target.handle(record) self.buffer = [] finally: self.release()
'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