⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 __init__.py

📁 xen虚拟机源代码安装包
💻 PY
📖 第 1 页 / 共 3 页
字号:
        """        Format the specified records and return the result as a string.        """        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#---------------------------------------------------------------------------#   Filter classes and functions#---------------------------------------------------------------------------class Filter:    """    Filter instances are used to perform arbitrary filtering of LogRecords.    Loggers and Handlers can optionally use Filter instances to filter    records as desired. The base filter class only allows events which are    below a certain point in the logger hierarchy. For example, a filter    initialized with "A.B" will allow events logged by loggers "A.B",    "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If    initialized with the empty string, all events are passed.    """    def __init__(self, name=''):        """        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.        """        self.name = name        self.nlen = len(name)    def filter(self, record):        """        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.        """        if self.nlen == 0:            return 1        elif self.name == record.name:            return 1        elif string.find(record.name, self.name, 0, self.nlen) != 0:            return 0        return (record.name[self.nlen] == ".")class Filterer:    """    A base class for loggers and handlers which allows them to share    common code.    """    def __init__(self):        """        Initialize the list of filters to be an empty list.        """        self.filters = []    def addFilter(self, filter):        """        Add the specified filter to this handler.        """        if not (filter in self.filters):            self.filters.append(filter)    def removeFilter(self, filter):        """        Remove the specified filter from this handler.        """        if filter in self.filters:            self.filters.remove(filter)    def filter(self, record):        """        Determine if a record is loggable by consulting all the filters.        The default is to allow the record to be logged; any filter can veto        this and the record is then dropped. Returns a zero value if a record        is to be dropped, else non-zero.        """        rv = 1        for f in self.filters:            if not f.filter(record):                rv = 0                break        return rv#---------------------------------------------------------------------------#   Handler classes and functions#---------------------------------------------------------------------------_handlers = {}  #repository of handlers (for flushing when shutdown called)class Handler(Filterer):    """    Handler instances dispatch logging events to specific destinations.    The base handler class. Acts as a placeholder which defines the Handler    interface. Handlers can optionally use Formatter instances to format    records as desired. By default, no formatter is specified; in this case,    the 'raw' message as determined by record.message is logged.    """    def __init__(self, level=NOTSET):        """        Initializes the instance - basically setting the formatter to None        and the filter list to empty.        """        Filterer.__init__(self)        self.level = level        self.formatter = None        #get the module data lock, as we're updating a shared structure.        _acquireLock()        try:    #unlikely to raise an exception, but you never know...            _handlers[self] = 1        finally:            _releaseLock()        self.createLock()    def createLock(self):        """        Acquire a thread lock for serializing access to the underlying I/O.        """        if thread:            self.lock = thread.allocate_lock()        else:            self.lock = None    def acquire(self):        """        Acquire the I/O thread lock.        """        if self.lock:            self.lock.acquire()    def release(self):        """        Release the I/O thread lock.        """        if self.lock:            self.lock.release()    def setLevel(self, level):        """        Set the logging level of this handler.        """        self.level = level    def format(self, record):        """        Format the specified record.        If a formatter is set, use it. Otherwise, use the default formatter        for the module.        """        if self.formatter:            fmt = self.formatter        else:            fmt = _defaultFormatter        return fmt.format(record)    def emit(self, 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.        """        raise NotImplementedError, 'emit must be implemented '\                                    'by Handler subclasses'    def handle(self, record):        """        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.        """        rv = self.filter(record)        if rv:            self.acquire()            try:                self.emit(record)            finally:                self.release()        return rv    def setFormatter(self, fmt):        """        Set the formatter for this handler.        """        self.formatter = fmt    def flush(self):        """        Ensure all logging output has been flushed.        This version does nothing and is intended to be implemented by        subclasses.        """        pass    def close(self):        """        Tidy up any resources used by the handler.        This version does removes the handler from an internal list        of handlers which is closed when shutdown() is called. Subclasses        should ensure that this gets called from overridden close()        methods.        """        #get the module data lock, as we're updating a shared structure.        _acquireLock()        try:    #unlikely to raise an exception, but you never know...            del _handlers[self]        finally:            _releaseLock()    def handleError(self, record):        """        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.        """        if raiseExceptions:            import traceback            ei = sys.exc_info()            traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr)            del eiclass StreamHandler(Handler):    """    A handler class which writes logging records, appropriately formatted,    to a stream. Note that this class does not close the stream, as    sys.stdout or sys.stderr may be used.    """    def __init__(self, strm=None):        """        Initialize the handler.        If strm is not specified, sys.stderr is used.        """        Handler.__init__(self)        if not strm:            strm = sys.stderr        self.stream = strm        self.formatter = None    def flush(self):        """        Flushes the stream.        """        self.stream.flush()    def emit(self, record):        """        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        [N.B. this may be removed depending on feedback]. If exception        information is present, it is formatted using        traceback.print_exception and appended to the stream.        """        try:            msg = self.format(record)            if not hasattr(types, "UnicodeType"): #if no unicode support...                self.stream.write("%s\n" % msg)            else:                try:                    self.stream.write("%s\n" % msg)                except UnicodeError:                    self.stream.write("%s\n" % msg.encode("UTF-8"))            self.flush()        except:            self.handleError(record)class FileHandler(StreamHandler):    """    A handler class which writes formatted logging records to disk files.    """    def __init__(self, filename, mode="a"):        """        Open the specified file and use it as the stream for logging.        """        StreamHandler.__init__(self, open(filename, mode))        self.baseFilename = filename        self.mode = mode    def close(self):        """        Closes the stream.        """        self.flush()        self.stream.close()        StreamHandler.close(self)#---------------------------------------------------------------------------#   Manager classes and functions#---------------------------------------------------------------------------class PlaceHolder:    """    PlaceHolder instances are used in the Manager logger hierarchy to take    the place of nodes for which no loggers have been defined. This class is    intended for internal use only and not as part of the public API.    """    def __init__(self, alogger):        """        Initialize with the specified logger being a child of this placeholder.        """        self.loggers = [alogger]    def append(self, alogger):        """        Add the specified logger as a child of this placeholder.        """        if alogger not in self.loggers:            self.loggers.append(alogger)##   Determine which class to use when instantiating loggers.#_loggerClass = Nonedef setLoggerClass(klass):    """    Set the class to be used when instantiating a logger. The class should    define __init__() such that only a name argument is required, and the    __init__() should call Logger.__init__()    """    if klass != Logger:        if not issubclass(klass, Logger):            raise TypeError, "logger not derived from logging.Logger: " + \                            klass.__name__    global _loggerClass    _loggerClass = klassclass Manager:    """    There is [under normal circumstances] just one Manager instance, which    holds the hierarchy of loggers.    """    def __init__(self, rootnode):        """        Initialize the manager with the root node of the logger hierarchy.        """        self.root = rootnode        self.disable = 0        self.emittedNoHandlerWarning = 0        self.loggerDict = {}    def getLogger(self, name):        """        Get a logger with the specified name (channel name), creating it        if it doesn't yet exist.        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.        """        rv = None        _acquireLock()        try:            if self.loggerDict.has_key(name):                rv = self.loggerDict[name]                if isinstance(rv, PlaceHolder):                    ph = rv                    rv = _loggerClass(name)                    rv.manager = self                    self.loggerDict[name] = rv                    self._fixupChildren(ph, rv)                    self._fixupParents(rv)            else:                rv = _loggerClass(name)                rv.manager = self                self.loggerDict[name] = rv                self._fixupParents(rv)        finally:            _releaseLock()        return rv    def _fixupParents(self, alogger):        """        Ensure that there are either loggers or placeholders all the way        from the specified logger to the root of the logger hierarchy.        """        name = alogger.name        i = string.rfind(name, ".")        rv = None        while (i > 0) and not rv:            substr = name[:i]            if not self.loggerDict.has_key(substr):                self.loggerDict[substr] = PlaceHolder(alogger)            else:                obj = self.loggerDict[substr]

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -