desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'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)
msg = self.format(record)
msg = ('From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s' % (self.fromaddr, ','.join(self.toaddrs), self.getSubject(record), formatdate(), msg))
if self.username:
if (self.secure is not None):
smtp.ehlo()
smtp.starttls(*self.secure)
smtp.ehlo()
smtp.login(self.username, self.password)
smtp.sendmail(self.fromaddr, self.toaddrs, msg)
smtp.quit()
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
|
'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 win32service.pyd.'
|
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
either need to override this method or place a suitable dictionary in
the handler\'s typemap attribute.'
|
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 (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
|
'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'):
|
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
|
'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 httplib, urllib
host = self.host
h = httplib.HTTP(host)
url = self.url
data = urllib.urlencode(self.mapLogRecord(record))
if (self.method == 'GET'):
if (url.find('?') >= 0):
sep = '&'
else:
sep = '?'
url = (url + ('%c%s' % (sep, data)))
h.putrequest(self.method, url)
i = host.find(':')
if (i >= 0):
host = host[:i]
h.putheader('Host', host)
if (self.method == 'POST'):
h.putheader('Content-type', 'application/x-www-form-urlencoded')
h.putheader('Content-length', str(len(data)))
h.endheaders((data if (self.method == 'POST') else None))
h.getreply()
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
|
'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.buffer = []
|
'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.'
|
def flush(self):
|
if self.target:
for record in self.buffer:
self.target.handle(record)
self.buffer = []
|
'Flush, set the target to None and lose the buffer.'
|
def close(self):
|
self.flush()
self.target = None
BufferingHandler.close(self)
|
'Initialize a logging record with interesting information.'
|
def __init__(self, name, level, pathname, lineno, msg, args, exc_info, func=None):
|
ct = time.time()
self.name = name
self.msg = msg
if (args and (len(args) == 1) and isinstance(args[0], dict) and args[0]):
args = args[0]
self.args = args
self.levelname = getLevelName(level)
self.levelno = level
self.pathname = pathname
try:
self.filename = os.path.basename(pathname)
self.module = os.path.splitext(self.filename)[0]
except (TypeError, ValueError, AttributeError):
self.filename = pathname
self.module = 'Unknown module'
self.exc_info = exc_info
self.exc_text = None
self.lineno = lineno
self.funcName = func
self.created = ct
self.msecs = ((ct - long(ct)) * 1000)
self.relativeCreated = ((self.created - _startTime) * 1000)
if (logThreads and thread):
self.thread = thread.get_ident()
self.threadName = threading.current_thread().name
else:
self.thread = None
self.threadName = None
if (not logMultiprocessing):
self.processName = None
else:
self.processName = 'MainProcess'
mp = sys.modules.get('multiprocessing')
if (mp is not None):
try:
self.processName = mp.current_process().name
except StandardError:
pass
if (logProcesses and hasattr(os, 'getpid')):
self.process = os.getpid()
else:
self.process = None
|
'Return the message for this LogRecord.
Return the message for this LogRecord after merging any user-supplied
arguments with the message.'
|
def getMessage(self):
|
if (not _unicode):
msg = str(self.msg)
else:
msg = self.msg
if (not isinstance(msg, basestring)):
try:
msg = str(self.msg)
except UnicodeError:
msg = 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).'
|
def __init__(self, fmt=None, datefmt=None):
|
if fmt:
self._fmt = fmt
else:
self._fmt = '%(message)s'
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) is specified,
it is used with time.strftime() to format the creation time of the
record. Otherwise, the ISO8601 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.'
|
def formatTime(self, record, datefmt=None):
|
ct = self.converter(record.created)
if datefmt:
s = time.strftime(datefmt, ct)
else:
t = time.strftime('%Y-%m-%d %H:%M:%S', ct)
s = ('%s,%03d' % (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 = cStringIO.StringIO()
traceback.print_exception(ei[0], ei[1], ei[2], 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._fmt.find('%(asctime)') >= 0)
|
'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.'
|
def format(self, record):
|
record.message = record.getMessage()
if self.usesTime():
record.asctime = self.formatTime(record, self.datefmt)
s = (self._fmt % record.__dict__)
if record.exc_info:
if (not record.exc_text):
record.exc_text = self.formatException(record.exc_info)
if record.exc_text:
if (s[(-1):] != '\n'):
s = (s + '\n')
try:
s = (s + record.exc_text)
except UnicodeError:
s = (s + record.exc_text.decode(sys.getfilesystemencoding()))
return s
|
'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 1
elif (self.name == record.name):
return 1
elif (record.name.find(self.name, 0, self.nlen) != 0):
return 0
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.'
|
def filter(self, record):
|
rv = 1
for f in self.filters:
if (not f.filter(record)):
rv = 0
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 thread:
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.'
|
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 system, they are more interested in application errors.
You could, however, replace this with a custom handler if you wish.
The record which was being processed is passed in to this method.'
|
def handleError(self, record):
|
if raiseExceptions:
ei = sys.exc_info()
try:
traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr)
sys.stderr.write(('Logged from file %s, line %s\n' % (record.filename, record.lineno)))
except IOError:
pass
finally:
del ei
|
'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):
|
if (self.stream and hasattr(self.stream, 'flush')):
self.stream.flush()
|
'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 determine how to do the
output to the stream.'
|
def emit(self, record):
|
try:
msg = self.format(record)
stream = self.stream
fs = '%s\n'
if (not _unicode):
stream.write((fs % msg))
else:
try:
if (isinstance(msg, unicode) and getattr(stream, 'encoding', None)):
ufs = fs.decode(stream.encoding)
try:
stream.write((ufs % msg))
except UnicodeEncodeError:
stream.write((ufs % msg).encode(stream.encoding))
else:
stream.write((fs % msg))
except UnicodeError:
stream.write((fs % msg.encode('UTF-8')))
self.flush()
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
|
'Open the specified file and use it as the stream for logging.'
|
def __init__(self, filename, mode='a', encoding=None, delay=0):
|
if (codecs is None):
encoding = None
self.baseFilename = os.path.abspath(filename)
self.mode = mode
self.encoding = encoding
if delay:
Handler.__init__(self)
self.stream = None
else:
StreamHandler.__init__(self, self._open())
|
'Closes the stream.'
|
def close(self):
|
if self.stream:
self.flush()
if hasattr(self.stream, 'close'):
self.stream.close()
StreamHandler.close(self)
self.stream = None
|
'Open the current base file with the (original) mode and encoding.
Return the resulting stream.'
|
def _open(self):
|
if (self.encoding is None):
stream = open(self.baseFilename, self.mode)
else:
stream = codecs.open(self.baseFilename, self.mode, self.encoding)
return stream
|
'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 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 = 0
self.loggerDict = {}
self.loggerClass = 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 and fix up the parent/child references which pointed to the
placeholder to now point to the logger.'
|
def getLogger(self, name):
|
rv = None
_acquireLock()
try:
if (name in self.loggerDict):
rv = self.loggerDict[name]
if isinstance(rv, PlaceHolder):
ph = rv
rv = (self.loggerClass or _loggerClass)(name)
rv.manager = self
self.loggerDict[name] = rv
self._fixupChildren(ph, rv)
self._fixupParents(rv)
else:
rv = (self.loggerClass or _loggerClass)(name)
rv.manager = self
self.loggerDict[name] = rv
self._fixupParents(rv)
finally:
_releaseLock()
return 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
|
'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):
rv = obj
else:
assert isinstance(obj, PlaceHolder)
obj.append(alogger)
i = name.rfind('.', 0, (i - 1))
if (not rv):
rv = self.root
alogger.parent = rv
|
'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 = 1
self.handlers = []
self.disabled = 0
|
'Set the logging level of this logger.'
|
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):
|
self.error(msg, exc_info=1, *args)
|
'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):
|
f = currentframe()
if (f is not None):
f = f.f_back
rv = ('(unknown file)', 0, '(unknown function)')
while hasattr(f, 'f_code'):
co = f.f_code
filename = os.path.normcase(co.co_filename)
if (filename == _srcfile):
f = f.f_back
continue
rv = (co.co_filename, f.f_lineno, co.co_name)
break
return rv
|
'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):
|
rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func)
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.__dict__[key] = extra[key]
return 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):
|
if _srcfile:
try:
(fn, lno, func) = self.findCaller()
except ValueError:
(fn, lno, func) = ('(unknown file)', 0, '(unknown function)')
else:
(fn, lno, func) = ('(unknown file)', 0, '(unknown function)')
if exc_info:
if (not isinstance(exc_info, tuple)):
exc_info = sys.exc_info()
record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra)
self.handle(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.'
|
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()
|
'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.'
|
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) and raiseExceptions and (not self.manager.emittedNoHandlerWarning)):
sys.stderr.write(('No handlers could be found for logger "%s"\n' % self.name))
self.manager.emittedNoHandlerWarning = 1
|
'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 0
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
LoggerAdapter subclass for your specific needs.'
|
def process(self, msg, kwargs):
|
kwargs['extra'] = self.extra
return (msg, kwargs)
|
'Delegate a debug call to the underlying logger, after adding
contextual information from this adapter instance.'
|
def debug(self, msg, *args, **kwargs):
|
(msg, kwargs) = self.process(msg, kwargs)
self.logger.debug(msg, *args, **kwargs)
|
'Delegate an info call to the underlying logger, after adding
contextual information from this adapter instance.'
|
def info(self, msg, *args, **kwargs):
|
(msg, kwargs) = self.process(msg, kwargs)
self.logger.info(msg, *args, **kwargs)
|
'Delegate a warning call to the underlying logger, after adding
contextual information from this adapter instance.'
|
def warning(self, msg, *args, **kwargs):
|
(msg, kwargs) = self.process(msg, kwargs)
self.logger.warning(msg, *args, **kwargs)
|
'Delegate an error call to the underlying logger, after adding
contextual information from this adapter instance.'
|
def error(self, msg, *args, **kwargs):
|
(msg, kwargs) = self.process(msg, kwargs)
self.logger.error(msg, *args, **kwargs)
|
'Delegate an exception call to the underlying logger, after adding
contextual information from this adapter instance.'
|
def exception(self, msg, *args, **kwargs):
|
(msg, kwargs) = self.process(msg, kwargs)
kwargs['exc_info'] = 1
self.logger.error(msg, *args, **kwargs)
|
'Delegate a critical call to the underlying logger, after adding
contextual information from this adapter instance.'
|
def critical(self, msg, *args, **kwargs):
|
(msg, kwargs) = self.process(msg, kwargs)
self.logger.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):
|
(msg, kwargs) = self.process(msg, kwargs)
self.logger.log(level, msg, *args, **kwargs)
|
'See if the underlying logger is enabled for the specified level.'
|
def isEnabledFor(self, level):
|
return self.logger.isEnabledFor(level)
|
'This method is called when there is the remote possibility
that we ever need to stop in this function.'
|
def user_call(self, frame, argument_list):
|
pass
|
'This method is called when we stop or break at this line.'
|
def user_line(self, frame):
|
pass
|
'This method is called when a return trap is set here.'
|
def user_return(self, frame, return_value):
|
pass
|
'Stop when the line with the line no greater than the current one is
reached or when returning from current frame'
|
def set_until(self, frame):
|
self._set_stopinfo(frame, frame, (frame.f_lineno + 1))
|
'Stop after one line of code.'
|
def set_step(self):
|
self._set_stopinfo(None, None)
|
'Stop on the next line in or below the given frame.'
|
def set_next(self, frame):
|
self._set_stopinfo(frame, None)
|
'Stop when returning from the given frame.'
|
def set_return(self, frame):
|
self._set_stopinfo(frame.f_back, frame)
|
'Start debugging from `frame`.
If frame is not specified, debugging starts from caller\'s frame.'
|
def set_trace(self, frame=None):
|
if (frame is None):
frame = sys._getframe().f_back
self.reset()
while frame:
frame.f_trace = self.trace_dispatch
self.botframe = frame
frame = frame.f_back
self.set_step()
sys.settrace(self.trace_dispatch)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.