📄 __init__.py
字号:
if isinstance(obj, Logger): rv = obj else: assert isinstance(obj, PlaceHolder) obj.append(alogger) i = string.rfind(name, ".", 0, i - 1) if not rv: rv = self.root alogger.parent = rv def _fixupChildren(self, ph, alogger): """ Ensure that children of the placeholder ph are connected to the specified logger. """ for c in ph.loggers: if string.find(c.parent.name, alogger.name) <> 0: alogger.parent = c.parent c.parent = alogger#---------------------------------------------------------------------------# Logger classes and functions#---------------------------------------------------------------------------class Logger(Filterer): """ Instances of the Logger class represent a single logging channel. A "logging channel" indicates an area of an application. Exactly how an "area" is defined is up to the application developer. Since an application can have any number of areas, logging channels are identified by a unique string. Application areas can be nested (e.g. an area of "input processing" might include sub-areas "read CSV files", "read XLS files" and "read Gnumeric files"). To cater for this natural nesting, channel names are organized into a namespace hierarchy where levels are separated by periods, much like the Java or Python package namespace. So in the instance given above, channel names might be "input" for the upper level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels. There is no arbitrary limit to the depth of nesting. """ def __init__(self, name, level=NOTSET): """ Initialize the logger with a name and an optional level. """ Filterer.__init__(self) self.name = name self.level = level self.parent = None self.propagate = 1 self.handlers = [] self.disabled = 0 def setLevel(self, level): """ Set the logging level of this logger. """ self.level = level# def getRoot(self):# """# Get the root of the logger hierarchy.# """# return Logger.root def debug(self, msg, *args, **kwargs): """ 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) """ if self.manager.disable >= DEBUG: return if DEBUG >= self.getEffectiveLevel(): apply(self._log, (DEBUG, msg, args), kwargs) def info(self, 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) """ if self.manager.disable >= INFO: return if INFO >= self.getEffectiveLevel(): apply(self._log, (INFO, msg, args), kwargs) def warning(self, 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) """ if self.manager.disable >= WARNING: return if self.isEnabledFor(WARNING): apply(self._log, (WARNING, msg, args), kwargs) warn = warning def error(self, 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) """ if self.manager.disable >= ERROR: return if self.isEnabledFor(ERROR): apply(self._log, (ERROR, msg, args), kwargs) def exception(self, msg, *args): """ Convenience method for logging an ERROR with exception information. """ apply(self.error, (msg,) + args, {'exc_info': 1}) def critical(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'CRITICAL'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.critical("Houston, we have a %s", "major disaster", exc_info=1) """ if self.manager.disable >= CRITICAL: return if CRITICAL >= self.getEffectiveLevel(): apply(self._log, (CRITICAL, msg, args), kwargs) fatal = critical def log(self, level, msg, *args, **kwargs): """ Log 'msg % args' with the 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) """ if self.manager.disable >= level: return if self.isEnabledFor(level): apply(self._log, (level, msg, args), kwargs) def findCaller(self): """ Find the stack frame of the caller so that we can note the source file name and line number. """ f = sys._getframe(1) while 1: co = f.f_code filename = os.path.normcase(co.co_filename) if filename == _srcfile: f = f.f_back continue return filename, f.f_lineno def makeRecord(self, name, level, fn, lno, msg, args, exc_info): """ A factory method which can be overridden in subclasses to create specialized LogRecords. """ return LogRecord(name, level, fn, lno, msg, args, exc_info) def _log(self, level, msg, args, exc_info=None): """ Low-level logging routine which creates a LogRecord and then calls all the handlers of this logger to handle the record. """ if _srcfile: fn, lno = self.findCaller() else: fn, lno = "<unknown file>", 0 if exc_info: if type(exc_info) != types.TupleType: exc_info = sys.exc_info() record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info) self.handle(record) def handle(self, 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. """ if (not self.disabled) and self.filter(record): self.callHandlers(record) def addHandler(self, hdlr): """ Add the specified handler to this logger. """ if not (hdlr in self.handlers): self.handlers.append(hdlr) def removeHandler(self, hdlr): """ Remove the specified handler from this logger. """ if hdlr in self.handlers: #hdlr.close() self.handlers.remove(hdlr) def callHandlers(self, record): """ 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. """ 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 #break out else: c = c.parent if (found == 0) and not self.manager.emittedNoHandlerWarning: sys.stderr.write("No handlers could be found for logger" " \"%s\"\n" % self.name) self.manager.emittedNoHandlerWarning = 1 def getEffectiveLevel(self): """ 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. """ logger = self while logger: if logger.level: return logger.level logger = logger.parent return NOTSET def isEnabledFor(self, level): """ Is this logger enabled for level 'level'? """ if self.manager.disable >= level: return 0 return level >= self.getEffectiveLevel()class RootLogger(Logger): """ A root logger is not that different to any other logger, except that it must have a logging level and there is only one instance of it in the hierarchy. """ def __init__(self, level): """ Initialize the logger with the name "root". """ Logger.__init__(self, "root", level)_loggerClass = Loggerroot = RootLogger(WARNING)Logger.root = rootLogger.manager = Manager(Logger.root)#---------------------------------------------------------------------------# Configuration classes and functions#---------------------------------------------------------------------------BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s"def basicConfig(): """ Do basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger. """ if len(root.handlers) == 0: hdlr = StreamHandler() fmt = Formatter(BASIC_FORMAT) hdlr.setFormatter(fmt) root.addHandler(hdlr)#---------------------------------------------------------------------------# Utility functions at module level.# Basically delegate everything to the root logger.#---------------------------------------------------------------------------def getLogger(name=None): """ Return a logger with the specified name, creating it if necessary. If no name is specified, return the root logger. """ if name: return Logger.manager.getLogger(name) else: return root#def getRootLogger():# """# Return the root logger.## Note that getLogger('') now does the same thing, so this function is# deprecated and may disappear in the future.# """# return rootdef critical(msg, *args, **kwargs): """ Log a message with severity 'CRITICAL' on the root logger. """ if len(root.handlers) == 0: basicConfig() apply(root.critical, (msg,)+args, kwargs)fatal = criticaldef error(msg, *args, **kwargs): """ Log a message with severity 'ERROR' on the root logger. """ if len(root.handlers) == 0: basicConfig() apply(root.error, (msg,)+args, kwargs)def exception(msg, *args): """ Log a message with severity 'ERROR' on the root logger, with exception information. """ apply(error, (msg,)+args, {'exc_info': 1})def warning(msg, *args, **kwargs): """ Log a message with severity 'WARNING' on the root logger. """ if len(root.handlers) == 0: basicConfig() apply(root.warning, (msg,)+args, kwargs)warn = warningdef info(msg, *args, **kwargs): """ Log a message with severity 'INFO' on the root logger. """ if len(root.handlers) == 0: basicConfig() apply(root.info, (msg,)+args, kwargs)def debug(msg, *args, **kwargs): """ Log a message with severity 'DEBUG' on the root logger. """ if len(root.handlers) == 0: basicConfig() apply(root.debug, (msg,)+args, kwargs)def disable(level): """ Disable all logging calls less severe than 'level'. """ root.manager.disable = leveldef shutdown(): """ Perform any cleanup actions in the logging system (e.g. flushing buffers). Should be called at application exit. """ for h in _handlers.keys(): h.flush() h.close()#Let's try and shutdown automatically on application exit...try: import atexit atexit.register(shutdown)except ImportError: # for Python versions < 2.0 def exithook(status, old_exit=sys.exit): try: shutdown() finally: old_exit(status) sys.exit = exithook
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -