desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Join the manager process (if it has been spawned)'
def join(self, timeout=None):
if (self._process is not None): self._process.join(timeout) if (not self._process.is_alive()): self._process = None
'Return some info about the servers shared objects and connections'
def _debug_info(self):
conn = self._Client(self._address, authkey=self._authkey) try: return dispatch(conn, None, 'debug_info') finally: conn.close()
'Return the number of shared objects'
def _number_of_objects(self):
conn = self._Client(self._address, authkey=self._authkey) try: return dispatch(conn, None, 'number_of_objects') finally: conn.close()
'Shutdown the manager process; will be registered as a finalizer'
@staticmethod def _finalize_manager(process, address, authkey, state, _Client):
if process.is_alive(): util.info('sending shutdown message to manager') try: conn = _Client(address, authkey=authkey) try: dispatch(conn, None, 'shutdown') finally: conn.close() except Exception: pass...
'Register a typeid with the manager type'
@classmethod def register(cls, typeid, callable=None, proxytype=None, exposed=None, method_to_typeid=None, create_method=True):
if ('_registry' not in cls.__dict__): cls._registry = cls._registry.copy() if (proxytype is None): proxytype = AutoProxy exposed = (exposed or getattr(proxytype, '_exposed_', None)) method_to_typeid = (method_to_typeid or getattr(proxytype, '_method_to_typeid_', None)) if method_to_t...
'Try to call a method of the referrent and return a copy of the result'
def _callmethod(self, methodname, args=(), kwds={}):
try: conn = self._tls.connection except AttributeError: util.debug('thread %r does not own a connection', threading.current_thread().name) self._connect() conn = self._tls.connection conn.send((self._id, methodname, args, kwds)) (kind, result) = conn.rec...
'Get a copy of the value of the referent'
def _getvalue(self):
return self._callmethod('#GETVALUE')
'Return representation of the referent (or a fall-back if that fails)'
def __str__(self):
try: return self._callmethod('__repr__') except Exception: return (repr(self)[:(-1)] + "; '__str__()' failed>")
'Register resource, returning an identifier.'
def register(self, send, close):
with self._lock: if (self._address is None): self._start() self._key += 1 self._cache[self._key] = (send, close) return (self._address, self._key)
'Return connection from which to receive identified resource.'
@staticmethod def get_connection(ident):
from .connection import Client (address, key) = ident c = Client(address, authkey=process.current_process().authkey) c.send((key, os.getpid())) return c
'Stop the background thread and clear registered resources.'
def stop(self, timeout=None):
from .connection import Client with self._lock: if (self._address is not None): c = Client(self._address, authkey=process.current_process().authkey) c.send(None) c.close() self._thread.join(timeout) if self._thread.is_alive(): u...
'Cleanup after any worker processes which have exited due to reaching their specified lifetime. Returns True if any workers were cleaned up.'
def _join_exited_workers(self):
cleaned = False for i in reversed(range(len(self._pool))): worker = self._pool[i] if (worker.exitcode is not None): util.debug(('cleaning up worker %d' % i)) worker.join() cleaned = True del self._pool[i] return cleaned
'Bring the number of pool processes up to the specified number, for use after reaping workers which have exited.'
def _repopulate_pool(self):
for i in range((self._processes - len(self._pool))): w = self.Process(target=worker, args=(self._inqueue, self._outqueue, self._initializer, self._initargs, self._maxtasksperchild, self._wrap_exception)) self._pool.append(w) w.name = w.name.replace('Process', 'PoolWorker') w.daemon =...
'Clean up any exited workers and start replacements for them.'
def _maintain_pool(self):
if self._join_exited_workers(): self._repopulate_pool()
'Equivalent of `func(*args, **kwds)`.'
def apply(self, func, args=(), kwds={}):
assert (self._state == RUN) return self.apply_async(func, args, kwds).get()
'Apply `func` to each element in `iterable`, collecting the results in a list that is returned.'
def map(self, func, iterable, chunksize=None):
return self._map_async(func, iterable, mapstar, chunksize).get()
'Like `map()` method but the elements of the `iterable` are expected to be iterables as well and will be unpacked as arguments. Hence `func` and (a, b) becomes func(a, b).'
def starmap(self, func, iterable, chunksize=None):
return self._map_async(func, iterable, starmapstar, chunksize).get()
'Asynchronous version of `starmap()` method.'
def starmap_async(self, func, iterable, chunksize=None, callback=None, error_callback=None):
return self._map_async(func, iterable, starmapstar, chunksize, callback, error_callback)
'Equivalent of `map()` -- can be MUCH slower than `Pool.map()`.'
def imap(self, func, iterable, chunksize=1):
if (self._state != RUN): raise ValueError('Pool not running') if (chunksize == 1): result = IMapIterator(self._cache) self._taskqueue.put((((result._job, i, func, (x,), {}) for (i, x) in enumerate(iterable)), result._set_length)) return result else: assert (chun...
'Like `imap()` method but ordering of results is arbitrary.'
def imap_unordered(self, func, iterable, chunksize=1):
if (self._state != RUN): raise ValueError('Pool not running') if (chunksize == 1): result = IMapUnorderedIterator(self._cache) self._taskqueue.put((((result._job, i, func, (x,), {}) for (i, x) in enumerate(iterable)), result._set_length)) return result else: ass...
'Asynchronous version of `apply()` method.'
def apply_async(self, func, args=(), kwds={}, callback=None, error_callback=None):
if (self._state != RUN): raise ValueError('Pool not running') result = ApplyResult(self._cache, callback, error_callback) self._taskqueue.put(([(result._job, None, func, args, kwds)], None)) return result
'Asynchronous version of `map()` method.'
def map_async(self, func, iterable, chunksize=None, callback=None, error_callback=None):
return self._map_async(func, iterable, mapstar, chunksize, callback, error_callback)
'Helper function to implement map, starmap and their async counterparts.'
def _map_async(self, func, iterable, mapper, chunksize=None, callback=None, error_callback=None):
if (self._state != RUN): raise ValueError('Pool not running') if (not hasattr(iterable, '__len__')): iterable = list(iterable) if (chunksize is None): (chunksize, extra) = divmod(len(iterable), (len(self._pool) * 4)) if extra: chunksize += 1 if (len(iter...
'Make sure that semaphore tracker process is running. This can be run from any process. Usually a child process will use the semaphore created by its parent.'
def ensure_running(self):
with self._lock: if (self._fd is not None): return fds_to_pass = [] try: fds_to_pass.append(sys.stderr.fileno()) except Exception: pass cmd = 'from multiprocessing.semaphore_tracker import main;main(%d)' (r, w) = os.pipe() ...
'Register name of semaphore with semaphore tracker.'
def register(self, name):
self._send('REGISTER', name)
'Unregister name of semaphore with semaphore tracker.'
def unregister(self, name):
self._send('UNREGISTER', name)
'Constructor. The optional \'locals\' argument specifies the dictionary in which code will be executed; it defaults to a newly created dictionary with key "__name__" set to "__console__" and key "__doc__" set to None.'
def __init__(self, locals=None):
if (locals is None): locals = {'__name__': '__console__', '__doc__': None} self.locals = locals self.compile = CommandCompiler()
'Compile and run some source in the interpreter. Arguments are as for compile_command(). One several things can happen: 1) The input is incorrect; compile_command() raised an exception (SyntaxError or OverflowError). A syntax traceback will be printed by calling the showsyntaxerror() method. 2) The input is incomplete...
def runsource(self, source, filename='<input>', symbol='single'):
try: code = self.compile(source, filename, symbol) except (OverflowError, SyntaxError, ValueError): self.showsyntaxerror(filename) return False if (code is None): return True self.runcode(code) return False
'Execute a code object. When an exception occurs, self.showtraceback() is called to display a traceback. All exceptions are caught except SystemExit, which is reraised. A note about KeyboardInterrupt: this exception may occur elsewhere in this code, and may not always be caught. The caller should be prepared to deal ...
def runcode(self, code):
try: exec code in self.locals except SystemExit: raise except: self.showtraceback()
'Display the syntax error that just occurred. This doesn\'t display a stack trace because there isn\'t one. If a filename is given, it is stuffed in the exception instead of what was there before (because Python\'s parser always uses "<string>" when reading from a string). The output is written by self.write(), below.'...
def showsyntaxerror(self, filename=None):
(type, value, tb) = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb if (filename and (type is SyntaxError)): try: (msg, (dummy_filename, lineno, offset, line)) = value.args except ValueError: pass else: va...
'Display the exception that just occurred. We remove the first stack item because it is our own code. The output is written by self.write(), below.'
def showtraceback(self):
try: (type, value, tb) = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb tblist = traceback.extract_tb(tb) del tblist[:1] lines = traceback.format_list(tblist) if lines: lines.insert(0, 'Traceback (most...
'Write a string. The base implementation writes to sys.stderr; a subclass may replace this with a different implementation.'
def write(self, data):
sys.stderr.write(data)
'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()